program story

좋은 API 또는 나쁜 API를 어떻게 정의합니까?

inputbox 2020. 11. 29. 10:25
반응형

좋은 API 또는 나쁜 API를 어떻게 정의합니까?


배경:

저는 제 대학에서 "Software Constraints"라는 수업을 듣고 있습니다. 첫 번째 강의에서 우리는 좋은 API를 구축하는 방법을 배웠습니다.

정말 나쁜 API 함수의 좋은 예는 public static void Select(IList checkRead, IList checkWrite, IList checkError, int microseconds);C # 의 소켓 입니다. 이 함수는 3 개의 소켓 목록을 수신하고이를 파괴하여 사용자가 .NET에 공급하기 전에 모든 소켓을 복제해야합니다 Select(). 또한 서버가 소켓을 기다릴 수있는 최대 시간을 설정하는 int 인 제한 시간 (마이크로 초)도 있습니다. 제한은 +/- 35 분입니다 (정수이므로).


질문 :

  1. API를 '나쁨'으로 정의하는 방법은 무엇입니까?
  2. API를 '좋은'것으로 정의하는 방법은 무엇입니까?

고려할 사항 :

  • 기억하기 어려운 함수 이름.
  • 이해하기 어려운 기능 매개 변수.
  • 잘못된 문서입니다.
  • 모든 것이 서로 연결되어 있으므로 한 줄의 코드를 변경해야하는 경우 실제로 다른 곳에서 수백 줄을 변경해야합니다.
  • 인수를 파괴하는 함수.
  • "숨겨진"복잡성으로 인해 확장 성이 떨어집니다.
  • 사용자 / 개발자에서 API를 사용할 수 있도록 래퍼를 빌드해야합니다.

API 디자인에서 저는 항상이 기조 연설이 매우 유용하다는 것을 발견했습니다
. 좋은 API를 디자인하는 방법과 중요한 이유-Joshua Bloch

여기에 발췌문이 있습니다. 전체 내용을 읽거나 비디오를 보는 것이 좋습니다.

II. 일반 원칙

  • API는 한 가지만 수행하고 잘 수행해야합니다.
  • API는 가능한 한 작지만 더 작아서는 안됩니다.
  • 구현이 API에 영향을주지 않아야 함
  • 모든 것의 접근성 최소화
  • Names Matter–API는 작은 언어입니다.
  • 문서 문제
  • 종교적으로 문서화
  • API 설계 결정의 성능 결과 고려
  • API 설계 결정이 성능에 미치는 영향은 실제적이고 영구적입니다.
  • API는 플랫폼과 평화롭게 공존해야합니다

III. 클래스 디자인

  • 가변성 최소화
  • 의미가있는 경우에만 하위 클래스
  • 상속을위한 설계 및 문서화 또는 금지

IV. 방법 설계

  • 클라이언트가 모듈이 할 수있는 일을하지 않도록하십시오
  • 최소 경악의 원칙을 위반하지 마십시오
  • 빠른 실패-오류 발생 후 최대한 빨리보고
  • 문자열 형식으로 사용 가능한 모든 데이터에 대한 프로그래밍 방식 액세스 제공
  • 주의해서 과부하
  • 적절한 매개 변수 및 반환 유형 사용
  • 여러 메서드에서 일관된 매개 변수 순서 사용
  • 긴 매개 변수 목록 피하기
  • 예외적 인 처리가 필요한 반환 값 방지

올바르게 사용하기 위해 문서를 읽을 필요는 없습니다.

멋진 API의 신호.


이 주제에 대해 많은 코딩 표준과 긴 문서 , 심지어 책 (Framework Design Guidelines) 이 작성되었지만이 중 대부분은 상당히 낮은 수준에서만 도움이됩니다.

맛의 문제도 있습니다. API는 어떤 룰북의 모든 규칙을 따를 수 있지만 다양한 유행하는 이데올로기를 철저히 준수하기 때문에 여전히 형편 없다. 최근의 범인은 패턴 지향으로, 싱글 톤 패턴 (초기화 된 전역 변수보다 약간 더 많음)과 팩토리 패턴 (구성을 매개 변수화하는 방법이지만 필요하지 않을 때 종종 구현 됨)이 과도하게 사용됩니다. 최근에는 IoC (Inversion of Control) 및 이와 관련된 작은 인터페이스 유형의 수가 증가하여 설계에 중복 된 개념적 복잡성을 추가 할 가능성이 더 높습니다.

취향을위한 최고의 튜터는 모방 (많은 코드와 API 읽기, 효과가있는 것과 효과가없는 것을 찾아 내기), 경험 (실수를하고 그로부터 배우는 것), 생각 (그 자체를 위해 유행하는 것을하지 말고, 행동하기 전에 생각하십시오).


  • 유용성-아직 충족되지 않은 (또는 기존 요구 사항을 개선) 요구 사항을 해결합니다.
  • 설명하기 쉬움-그것이하는 일에 대한 기본적인 이해는 이해하기 간단해야합니다.
  • 일부 문제 영역 또는 실제 세계의 일부 개체 모델을 따릅니다. 의미있는 구조를 사용합니다.
  • 동기 및 비동기 호출의 올바른 사용. (시간이 걸리는 것을 막지 마십시오)
  • 좋은 기본 동작-가능한 경우 확장 성과 조정을 허용하지만 간단한 경우에 필요한 모든 것에 대한 기본값을 제공합니다.
  • 샘플 사용 및 작동하는 샘플 애플리케이션. 이것은 아마도 가장 중요 할 것입니다.
  • Excellent documentation
  • Eat your own dog food (if applicable)
  • Keep it small or segment it so that it is not one huge polluted space. Keep functionality sets distinct and isolated with few if any dependencies.

There are more, but that is a good start


A good API has a semantic model close to the thing it describes.

For example, an API for creating and manipulating Excel spreadsheets would have classes like Workbook, Sheet, and Cell, with methods like Cell.SetValue(text) and Workbook.listSheets().


A good API allows the client to do pretty much everything they need to do, but doesn't require them to do a lot of mindless busy-work. Examples of "mindless busy work" would be initializing data structure fields, calling several routines in a sequence that never varies with no real custom code in between, etc.

The surest sign of a bad API is if your clients all want to wrap it with their own helper code. At the absolute least, your API should have provided that helper code. Most likely, it should have been designed to provide the higher level of abstraction the clients are rolling themselves on their own every time.


I've always liked this article in queue titled API Design Matters

http://queue.acm.org/detail.cfm?id=1255422

And this columns also that deals with API design issues:

http://queue.acm.org/detail.cfm?id=1229903


A bad API is one that is not used by its intended audience.

A good API is one that is used by its intended audience for the purpose for which it was designed.

A great API is one that is used by both its intended audience, for the its intended purpose, and an unintended audience for reasons unanticipated by its designers.

If Amazon publishes its API as both SOAP and REST, and the REST version wins out, that doesn't mean the underlying SOAP API was bad.

I'd imagine that the same will be true for you. You can read all you want about design and try your best, but the acid test will be use. Spend some time building in ways to get feedback on what works and what doesn't and be prepared to refactor as needed to make it better.


A good API is one that makes simple things simple (minimum boilerplate and learning curve to do the most common things) and complicated things possible (maximum flexibility, as few assumptions as possible). A mediocre API is one that does one of these well (either insanely simple but only if you're trying to do really basic stuff, or insanely powerful, but with a really steep learning curve, etc). A horrible API is one that does neither of these well.


There are several other good answers on this already, so I thought I'd just throw in some links I didn't see mentioned.

Articles

  1. "A Little Manual Of API Design" by Jasmin Blanchette of Trolltech
  2. "Defining QT-Style C++ APIs" also Trolltech

Books:

  1. "Effective Java" by Joshua Bloch
  2. "The Practice Of Programming" by Kernighan and Pike

I think a good API should allow custom IO and memory management hooks if it's applicable.

A typical example is you have your custom compressed archive format for data on disk and a third party library with a poor api wants to access data on disk and expects a path to a file where it can load its data.

This link has some good points: http://gamearchitect.net/2008/09/19/good-middleware/


If the API produces an error message, ensure that the message and diagnostics help a developer work out what the problem is.

My expectation is that the caller of an API passes in input that is correct. A developer is the consumer of any error messages produced by the API (not the end user), and messages aimed at the developer help the developer debug their calling program.


An API is bad when it is badly documented.

An API is good when it is well documented and follows a coding standard.

Now these are two, very simple and also very hard points to follow, this brings one into the area of software architecture. You need a good architect that structures the system and helps the framework follow its own guidlines.

Commenting code, writing an well explained manual for the API is Mandatory.

An API can be good if it has a good documentation which explains how to use it. But if the code is clean, good and follows a standard inside itself, it doesnt matter if it doenst have a decent documentation.

I've written a little about coding structure here


I think what is paramount is readability, by which I mean the quality that makes the greatest number of programmers to make sense of what the code is doing in the shortest possible amount of time. But judging which piece of software is readable and which is not has that indescribable human quality: fuzziness. The points you mention do partly succeed in crystallizing it. However, in its entirety it has to remain a case-by-case affair and it would be really hard to come up with universal rules.

참고URL : https://stackoverflow.com/questions/469161/how-do-you-define-a-good-or-bad-api

반응형