ZLBL.com!
Enjoy blogging everywhere!

죠슈아 블록의 API설계에 대한 조언

명인(Joshua Bloch)이 얘기하는 API 설계에 대한 조언.

Joshua Bloch은 현재 구글에서 Chief Java Architect이며, Sun재직시절 Java Collection Framework등
많은 부분을 Design하고 구현한 대표적인 Java 전문가이자 architect입니다.
그가 말하는 주옥 같은 격언들입니다. 짧으니깐 한번씩 꼭 보시길.
굳이 발번역까지 했습니다.

Joshua Bloch: Bumper-Sticker API Design
Posted by Joshua Bloch on Sep 22, 2008
from INFOQ.com
Community

원본링크 ( http://www.infoq.com/articles/API-Design-Joshua-Bloch )

My conference session How to Design a Good API and Why it Matters has always drawn large crowds; on InfoQ was the third most viewed content last year. When I presented this session as an invited talk at OOPSLA 2006, I was given the opportunity to write an abstract for the proceedings. In place of an ordinary abstract I decided to try something a bit unusual: I distilled the essence of the talk down to a modest collection of pithy maxims, in the spirit of Jon Bentley’s classic Bumper-Sticker Computer Science, Item 6 in his excellent book, More Programming Pearls: Confessions of a Coder (Addison-Wesley, 1988).
RelatedVendorContent
It is my hope that these maxims provide a concise summary of the key points of API design, in easily digestible form:

  • 모든 프로그래머는 API디자이너다. 좋은 프로그램은 모듈단위로 구성되며, 모듈간 경계는 API로 정의된다. 좋은 모듈은 재사용된다.
    All programmers are API designers. Good programs are modular, and intermodular boundaries define APIs. Good modules get reused.
  • API는 당신의 가장 큰 자산이 될 수도 부채가 될 수도 있다. 좋은 API는 장기적인 사용자를 만들지만, 나쁜 API는 허구헌날 봐줘야하는 악몽이 된다.
    APIs can be among your greatest assets or liabilities. Good APIs create long-term customers; bad ones create long-term support nightmares.
  • 공개 API는 다이아몬드처럼 영원하다.제대로 할 기회는 한번뿐이며, 따라서 최선을 다하라.
    Public APIs, like diamonds, are forever. You have one chance to get it right so give it your best.
  • API는 쓰기 쉬워야 하며, 잘못 쓰기도 어렵게 하라. 간단한 일은 쉽게 할 수 있어야 하며, 복잡한 일도 가능해야 한다. 그리고 잘못된 동작은 아예 불가능하거나 최소한 어렵도록 해야한다.
    APIs should be easy to use and hard to misuse. It should be easy to do simple things; possible to do complex things; and impossible, or at least difficult, to do wrong things.
  • API는 자체가 문서여야 한다. 좋은 API로 작성된 코드는 읽을때 문서가 거의 필요 없어야 하며, 사실 API를 사용할때도 문서 자체가 별로 필요없어야 한다.
    APIs should be self-documenting: It should rarely require documentation to read code written to a good API. In fact, it should rarely require documentation to write it.
  • 처음 API를 디자인 할때, 우선 건전한 비판이 포함된 요구사항을 수집해봐라. 사람들은 종종 해결책까지 제시하기도 한다. 물론 그 해결책들에 잠재된 문제를 찾아내서 최고를 찾는건 당신 일이다.
    When designing an API, first gather requirements—with a healthy degree of skepticism. People often provide solutions; it’s your job to ferret out the underlying problems and find the best solutions.
  • 요구사항을 유스케이스등으로 구조화 하라. 나중에 API를 측정할때 “자”와 같은 것이 될 것이다.
    Structure requirements as use-cases: they are the yardstick against which you’ll measure your API.
  • API의 초기안은 짧아야 하며, 일반적으로 한 페이지의 클래스와 Method등 그리고 한줄짜리 설명정도면 좋다. 이렇게 하면 처음에 잘못하더라도 API를 재구성 하기가 쉽다.
    Early drafts of APIs should be short, typically one page with class and method signatures and one-line descriptions. This makes it easy to restructure the API when you don’t get it right the first time.
  • 구현전에 당신의 API를 사용하는 코드를 먼저 짜보라, 심지어 제대로 정의하기전에도 괜찮다. 이렇게 하면 애당초 잘못된 API를 괜히 구현하거나 정의하는 수고를 최소화 할 수 있다.
    Code the use-cases against your API before you implement it, even before you specify it properly. This will save you from implementing, or even specifying, a fundamentally broken API.
  • API를 발전시켜나갈때 항상 Use-Case들를 위한 코드는 유지하라. 이렇게 하면 구현 중 황당한 일(버그등)을 안만날 뿐 아니라, 샘플 코드로서 기능은 물론이고, 설명서의 기본 틀이자, 테스트 코드가 될 것이다.
    Maintain the code for uses-cases as the API evolves. Not only will this protect you from rude surprises, but the resulting code will become the examples for the API, the basis for tutorials and tests.
  • 예제 코드는 모범적이며, 전형적인 API사용이어야 한다. 나중에 API가 널리 퍼지게 되면 예제 코드들은 수천개의 코드에 사용되는 원형이 될것이다. (예제 코드의) 작은 실수는 수천배의 괴로움으로 돌아올 것이다.
    Example code should be exemplary. If an API is used widely, its examples will be the archetypes for thousands of programs. Any mistakes will come back to haunt you a thousand fold.
  • 만인을 만족시킬 수는 없다. 따라서 모든 사람들 공평하게 덜 불편하게 하는것을 목표로 하라. 대부분의 API들은 조건이 너무 많다.
    You can’t please everyone so aim to displease everyone equally. Most APIs are overconstrained.
  • 미쳐 생각을 못했기 때문에 나타날 수 있는 API실수를 대비하라. 사람들이 이 API를 가지고 무슨 짓을 할지를 모두 상상할 수 없다. 또한 시스템의 다른 부분과 어떻게 동작할 지도 모두 예상할 수 없다.
    Expect API-design mistakes due to failures of imagination. You can’t reasonably hope to imagine everything that everyone will do with an API, or how it will interact with every other part of a system.
  • API설계는 혼자하는 활동이 아니다. 가능하면 많은 사람에게 보여주고 그사람들의 Feedback을 진지하게 받아들여라. 당신이 상상하지 못한 가능성이 다른 사람에게는 잘 보일지도 모른다.
    API design is not a solitary activity. Show your design to as many people as you can, and take their feedback seriously. Possibilities that elude your imagination may be clear to others.
  • 입력크기제한을 하드 코딩하지 말라. 그렇게 하면 유용성을 제한하게 되며, 훨씬 더 빨리 못쓰게 된다.
    Avoid fixed limits on input sizes. They limit usefulness and hasten obsolescence.
  • 이름은 중요하다.단순명쾌하고 일관되고 대칭적인 이름을 찾도록 노력하라. 모든 API는 하나의 작은 언어이며, 사람들은 그걸 배워서 읽고 써야 한다. 제대로 된 API라면, 코드는 소설글처럼 쉽게 읽힐 것이다.
    Names matter. Strive for intelligibility, consistency, and symmetry. Every API is a little language, and people must learn to read and write it. If you get an API right, code will read like prose.
  • 좋은 이름들 도저히 못 찾겠으면, 초기 단계로 돌아가라. API를 분리하거나 합치거나 더 일반적인 API에 포함시키는 것을 두려워 하지 마라. 이름이 딱딱 제자리에 맞아 들어가면 제대로 가고 있는 것이다.
    If it’s hard to find good names, go back to the drawing board. Don’t be afraid to split or merge an API, or embed it in a more general setting. If names start falling into place, you’re on the right track.
  • 긴가민가하면, 빼버려라.API 설계의 가장 기본이 되는 법칙이 있다면, 바로 이것이다. 이 법칙은 기능, 클래스, Method, 인수에 모두 똑같이 적용된다. 모든 면에서 봤을때 API는 가능한 한 작게하라. 하지만 너무 작게는 하지 말아라. 항상 추가는 가능하지만 빼버리는 것은 어렵다. 개념적인 무게를 줄이는 것이 클래스 수나 Method 수를 줄이는것보다 더 중요하다.
    When in doubt, leave it out. If there is a fundamental theorem of API design, this is it. It applies equally to functionality, classes, methods, and parameters. Every facet of an API should be as small as possible, but no smaller. You can always add things later, but you can’t take them away. Minimizing conceptual weight is more important than class- or method-count.
  • API는 세부구현에 무관하게 유지하라. 구현방안들은 사용자를 헷갈리게 하고 유연성을 제한한다. 무엇이 세부구현인지는 항상 명백한건 아니다: 오버스펙에 대해서 주의하라.
    Keep APIs free of implementations details. They confuse users and inhibit the flexibility to evolve. It isn’t always obvious what’s an implementation detail: Be wary of overspecification.
  • 변경가능성은 최소화 하라. 내부값이 변하지 않는 객체(Immutable object)가 간단하며, Multithread 대응되며 마음껏 공유가능하다.
    Minimize mutability. Immutable objects are simple, thread-safe, and freely sharable.
  • 문서화는 중요하다.아무리 API가 좋아도 좋은 문서가 없으면 쓰이지 않는다. 모든 API의 외부 Interface요소를 설명하라: 모든 클래스, 모든 method, 모든 변수, 모든 인수.
    Documentation matters. No matter how good an API, it won’t get used without good documentation. Document every exported API element: every class, method, field, and parameter.
  • API설계시 결정되는 성능 문제를 고려하라. 하지만 성능문제때문에 API를 뒤틀진 마라. 다행히도 좋은 API는 구현시에 성능 향상을 시키는게 가능하다.
    Consider the performance consequences of API design decisions, but don’t warp an API to achieve performance gains. Luckily, good APIs typically lend themselves to fast implementations.
  • 로마에 가면, 로마인이 하는대로 하라 API는 반드시 플랫폼과 평화적으로 공존해야 하며, 그렇게 하는것이 불문율이다. 한 플랫폼에서 다른 플랫폼으로 API를 곧이 곧대로 옮기는건 항상 문제가 생긴다.
    When in Rome, do as the Romans do. APIs must coexist peacefully with the platform, so do what is customary. It is almost always wrong to “transliterate” an API from one platform to another.
  • 접근성을 최소화 하라잘모르겠으면, private으로 만들어라. 이렇게 해야 API가 간결해지며, 연관성(coupling)이 줄어든다.
    Minimize accessibility; when in doubt, make it private. This simplifies APIs and reduces coupling.
  • 클래스 상속은 하위 클래스의 모든 instance는 상위클래스의 instance이다라고 자신있게 말할 수 있을때만 쓰라.구현부분만 재사용하기 위해 클래스를 상속하진 말라.
    Subclass only if you can say with a straight face that every instance of the subclass is an instance of the superclass. Exposed classes should never subclass just to reuse implementation code.
  • 상속을 위한 설계와 문서를 작성하고 그렇지 않은 경우는 금지하라이 문서들은 “특정 클래스의 method들이 다른 클래스를 어떻게 사용하는가” 식의 형식을 띄게 된다. 이런 문서 없이 제대로된 클래스 상속은 불가능하다.
    Design and document for inheritance or else prohibit it. This documentation takes the form of selfuse patterns: how methods in a class use one another. Without it, safe subclassing is impossible.
  • library가 할수 있다고 해서 API사용자가 마음대로 사용하게 두지 말라.이런 원칙이 없으면, API사용자는 또다시 반복 코드를 재작성하게 되고 이건 대부분 짜증나는 부분이며 에러 또한 많이 마련이다.
    Don’t make the client do anything the library could do. Violating this rule leads to boilerplate code in the client, which is annoying and error-prone.
  • 최소놀람의 원칙을 지켜라. 모든 메소드는 주어진 이름에 맞도록 동작해야 하며, 가능하면 예기치 못한 일이 발생하지 않도록 해야한다. 어떤 메소드가 사용자가 생각한대로 동작하지 않으면 결국 버그로 이어진다.
    Obey the principle of least astonishment. Every method should do the least surprising thing it could, given its name. If a method doesn’t do what users think it will, bugs will result.
  • 빨리 실패시켜라. 버그를 빨리 보고할수록 피해는 적다. 컴파일할때가 제일 좋다. 런타임시 실패하면 가능하면 빨리(실행초기) 실패하도록 해라.
    Fail fast. The sooner you report a bug, the less damage it will do. Compile-time is best. If you must fail at run-time, do it as soon as possible.
  • 문자열에 있는 데이터를 프로그램적으로 접근할 수 있도록 해라.프로그래머가 일일이 문자열을 파싱해야한다면 그건 끔찍한 일이다. 더 최악은 그 문자열 형식이 사실상 또하나의 API가 되어버린다.
    Provide programmatic access to all data available in string form. Otherwise, programmers will be forced to parse strings, which is painful. Worse, the string forms will turn into de facto APIs.
  • 오버로딩은 신중하게해라. 두 메소드의 동작이 다르다면, 이름을 다르게 하는게 낫다.
    Overload with care. If the behaviors of two methods differ, it’s better to give them different names.
  • 적합한 데이터 타입을 사용하라.더 적합한 타입이 있을 때는 문자열을 사용하지 말라.
    Use the right data type for the job. For example, don’t use string if there is a more appropriate type.
  • 여러 메소드에 걸쳐 비슷한 파라미터면 순서까지 유지하도록 해라. 그렇지 않다면, 프로그래머는 거꾸로 알아 들을 것이다.
    Use consistent parameter ordering across methods. Otherwise, programmers will get it backwards.
  • 파라미터 목록은 길어지도록 하지 말라. 특히 동일한 타입의 연속된 파라미터는 피하라. String, String, String등
    Avoid long parameter lists, especially those with multiple consecutive parameters of the same type.
  • Exception처리가 필요한 return value는 피하라. 사용자는 보통 특수케이스 처리코드는 빼먹고 작성안하기 쉽상이다. 예를 들어 Null value보다는 길이가 0인 배열이나 collection이 낫다.
    Avoid return values that demand exceptional processing. Clients will forget to write the specialcase code, leading to bugs. For example, return zero-length arrays or collections rather than nulls.
  • Exception은 반드시 예외적인 상황에서는 사용하라. 일반적인 상황까지 Exception을 사용하면, 그 프로그램은 읽기 어렵고, 버그가 많으며, 느리기까지 하다.
    Throw exceptions only to indicate exceptional conditions. Otherwise, clients will be forced to use exceptions for normal flow control, leading to programs that are hard to read, buggy, or slow.
  • 사용자가 정말 실패에서 복구할수 있는게 아니라면, 체크안된 Exception들을 던져라.
    Throw unchecked exceptions unless clients can realistically recover from the failure.<

  • /strong>

    API 설계는 과학이 아니라 하나의 예술이다. 아름다움을 위해 노력하고, 자신의 감을 믿어라. 위의 조언들을 무식하게 따르지 말고, 충분한 이유가 생겼을땐 가끔 무시하라.
    API design is an art, not a science. Strive for beauty, and trust your gut. Do not adhere slavishly to the above heuristics, but violate them only infrequently and with good reason.

Watch Presentation: How to Design a Good API & Why it Matters

Joshua Bloch is Chief Java Architect at Google, author of Effective Java, Second Edition (Addison-Wesley, 2008), and coauthor of Java Puzzlers: Traps, Pitfalls, and Corner Cases (Addison-Wesley, 2005) and Java Concurrency in Practice. He was a Distinguished Engineer at Sun Microsystems, where he led the design and implementation of numerous Java platform features including JDK 5.0 language enhancements and the Java Collections Framework. He holds a Ph.D. from Carnegie-Mellon and a B.S from Columbia.


Posted by kaicy on October 31st, 2010 :: Filed under 끄적끄적

작품번호의 유래

퍼온글: http://blog.daum.net/kokokiry/18342383

보통 클래식 음악에는 Op.라는 작품번호가 붙는다. 이는 ‘작품’을 의미하는 라틴어 Opus의 약자이다. 그러나 몇몇 작곡가들의 작품 앞에는 위대한 작곡가들의 수많은 작품을 분류, 확인하여 정리한 음악학자들의 이니셜을 따거나, 작곡가의 이름에서 유래한 고유의 작품 번호가 붙는다. Op.와 고유의 작품번호를 같이 쓰는 경우도 있고, 같은 곡이라도 분류한 사람에 따라 다른 작품번호를 쓰는 경우도 있다.

음악 작품에 따르는 번호는 크게 두가지가 있다.
하나는 장르별 일련번호이고 또 하나는 그 작곡가의 모든 작품에 순차적으로 붙이는 작품번호 오퍼스(Opus, Op.)이다.

Opus는 출판 순서대로
물론 베토벤의 후기 현악 4중주들은 작품번호와 작곡순서가 일치하지 않습니다. 그런데도 작품 번호가 일반적으로 통용되는 이유는, 굳이 다른 일련 번호를 만들지 않아도 되며 (다른 번호를 만든다면 이에 익숙해지는 데 상당히 시간이 필요하죠) 대체로 출판 순서와 작곡 순서가 잘 맞아, 가끔 역전된 것이 있더라도 ‘대세에 지장을 줄 정도로’ 심각한 것은 아니라는 이유 때문에 아직 Opus 번호가 통용됩니다. 물론 초기 작품들이 나중에 출판되어 Op.103같은 번호를 달고 나오기도 하는데, 중요한 작품들의 경우는 대강 순서가 맞습니다. 이런 작품을 소개할 때는 물론 몇년에 작곡되었다고 단서를 달아야지요. 슈베르트 같은 경우에는 절대로 Opus를 믿을 수가 없습니다만, 베토벤은 꽤쓸만 합니다. 단 중요하지 않다고 베토벤이 생각한 작품의 경우는 Opus 대신 WoO(Werke ohne opus, 작품 번호 없는 작품)를 달고 출판되었기 때문에, 번호가 2중으로 붙는 문제점은 있지요. 아마 브람스는 거의 Opus가 작곡 순서와 일치합니다.

바흐, Johann Sebastian Bach
BWV : Bach가 죽은지 200년이 되던 해인 1950년, 독일의 볼프강 슈미더 (Wolfgang Schmieder: 1901~ )가 Bach의 작품들을 정리한 목록을 출판했다. 그의 목록에는 ‘바흐의 작품 목록’이라는 뜻의 독일어 ‘Bach – Werke – Verzeichnis’의 이니셜을 따 BWV라는 작품 번호가 붙었다. BWV는 총 1120개의 Bach 작품에 붙어있다.

ex) Partita No.2 in D minor, BWV1004 (파르티타 2번 D단조)
Anh. : “Anhang(추가, 혹은 추가의 의미)”의 약어로 작품목록 작성 후에 추가한 작품에 붙여진 번호를 말한다.
ex) Menuett, BWV Anh.113

모차르트, Wolfgang Amadeus Mozart
K : 모차르트의 작품에 가장 빈번히 사용되는 K는 오스트리아의 모차르트 연구가 루드비히 폰 쾨헬(Kochel : 1780~1677)의 이니셜을 딴 것이다. 그는 총 626곡의 모차르트 작품에 번호를 매겼다. K는 종종 ‘쾨헬 작품 목록’이라는 의미의 Kochel – Verzeichnis의 이니셜을 따서 ‘KV’로 표기되기도 한다.
ex) Sonata No.11 in A major, K.331


Posted by kaicy on January 20th, 2009 :: Filed under 읽을거리
Tags :: , ,

MP3편집기 Audacity깔기.

간단한 편집을 할때 유용한 Audacity받아서 깔기 정리합니다. (windows용)

1. Audacity download
홈페이지에서 직접 받기. (클릭)
또는 Audacity 1.2.6 installer 누르시고 오른쪽 클릭해서 저장.
실행하여 설치.

2. MP3로 저장하기 위한 DLL 파일 받기.
LAME홈페이지에서 받기 (다운로드페이지)
또는 libmp3lame-win-3.98.2.zip 누르시고 오른쪽 클릭해서 저장.
추가로 적당한 위치에 압축 풀어놓기 (예를들어 C:\Program Files\Audacity\Plug-Ins)

3. Audacity 실행
4. MP3불러 온후 편집
5. MP3로 저장하기는 다음과 같이.
File/Export as MP3메뉴 클릭.
처음 실행한 경우 아까 받은 DLL이 필요하다고 경고창이 뜹니다.
(어쩌고어쩌고 마지막에 Would like to locate lame_enc.dll now?)
이때 Yes하시고 2번에서 저장한 folder를 지정하시면 됩니다.

끝.


Posted by kaicy on January 15th, 2009 :: Filed under 놀거리(쪼물딱쪼물딱)
Tags :: , , ,

PC vs Mac

와우 정말 잘 만들었네요.


Posted by kaicy on December 30th, 2008 :: Filed under 볼거리
Tags :: , ,

Nostalgia, 요조 w/ 에릭

오늘 퇴근길 이소라의 오후의 발견 마지막곡이었죠.
요조양의 목소리가 매우 매력적인 곡입니다. 요조양의 다른 곡과는 달리 힘이 더 들어간게
어딘가 As One과 닮았다고 생각했네요. ^^ 맘에 듭니다.
가사도 좋아요. ^^ “구름위를 걸어가는 기분 바다위를 걷는 자유로움”


요조 – Nostalgia

Brown classic yeah til the day we die you heard me?
nothing can ever changes you already know

내밀었지 커다란 너의 손 자꾸 웃음이 나와
달콤한 초콜릿 멜로디 내 머릴 만지네
나를향한 너의 투명했던 눈빛 휘파람을 불렀지
눈을 감고 너를 보고 있는 날 따듯하게 감싸주네
운명은 이렇게 갑자기 나를 찾아왔지 설레임 깊은 잠을 깨워
구름위를 걸어가는 기분 바다위를 걷는 자유로움

I′ma say you love is like a toxic 천천히 스며들었어 완전히 사로잡았지
I need glasses 가까이 보고싶은맘 what you know about that
I′ve been taking classes 널 사로잡기 위한 Lession
I got my crips and cars Dosen′t mean nothing but nothing is everything
So relax we′re brown classics What it is yo, we stratch like electrics

너를 향해 내가 꿈꿔왔던 구름 차츰 내게 다가와
눈을 감고 너를 보고 있는 날 따듯하게 감싸주네
운명은 이렇게 갑자기 나를 찾아왔지 설레임 깊은 잠을 깨워
구름위를 걸어가는 기분 바다위를 걷는 자유

시간이 흐른뒤에 지금처럼만 내 곁에 있어줘
함께 걸어 나를 기다린 끝없는 하늘
감출수 없는 이 커다란 이 커다란 행복
운명은 이렇게 갑자기 나를 찾아왔지 설레임 깊은 잠을 깨워

구름위를 걸어가는 기분 바다위를 걷는 자유로움
사랑은 이렇게 커다란 행복을 주는것 운명은 나를 더 가볍게
구름위를 걸어가는 기분 바다위를 걷는 자유로움


Posted by kaicy on December 26th, 2008 :: Filed under 들을거리
Tags :: ,

와우. 근성의 Sticky Note 동영상.

28만장의 Sticky Note(Post-It같은거)를 사용했다네요.
대단합니다!!


Posted by kaicy on October 3rd, 2008 :: Filed under 놀거리(쪼물딱쪼물딱)
Tags :: , ,

원더걸스 Nobody 뮤비

정말 박진영 귀에 쏙쏙들어오는 곡만드는 실력하난 알아줘야겠네요.
흥겹습니다. 쿵따 쿵따닥~

뮤직비디오도 살짝쿵 재밌네요. ㅋㅋㅋ “저기요~~”


Posted by kaicy on September 27th, 2008 :: Filed under 들을거리
Tags :: , ,