At Javapolis, Joshua Bloch gave a presentation about designing a good API. Joshua starts by defining why designing a good API matters. An API is as asset. A public API if forever. You have once chance to get it right. If it is well written, it will capture and hook customers, while a badly written one will result in an endless barrage of support calls. Good software is modular and each module should have a well defined API. A good API is one that satisfies the requirements of the appropriate audience. It is easy to learn and use while hard to misuse. The code is readable, maintainable, and extendable.
Then Joshua covers some general principles:
· API should do one thing and do it well. Functionality should be easy to name.
· API should be as small as possible. When in doubt, leave it out, as it is easy to add it later, but you can never remove it. Look for a good power to weight ratio.
· Implementation details should not impact API
· Minimize accessibility of everything. Make classes and members as private as possible. Allow classes to be used, understood, built, tested, and debugged independently.
· Names matter. Avoid cryptic abbreviations. Be consistent. Strive for symmetry.
· Documentation matters. Document religiously. Document every class, interface, method,
constructor, parameter, and exception.
· Consider Performance consequences of API decision on performance. Bad decisions include making types mutable, using constructors instead of factories, and using implementation instead of interface
· API must coexist peacefully with platform. Obey naming conventions, avoid obsolete types, mimic patterns and take advantage of core API and language features while avoiding language pitfalls.
Next Joshua covers class design and emphasizes minimizing mutability, subclassing only when it makes sense (Liskov), and designing and document for inheritance, otherwise prohibiting it.
For method design:
· Don’t make the client do anything the module could do
· Don’t violate the principle of least astonishment
· Fail Fast- report errors as soon as possible after they occur.
· Provide programmatic access to all data available string form
· Overload with care: just because you can does not mean you should.
· Use consistent parameter ordering across methods.
· Avoid long parameter lists
· Avoid return values that demand exceptional processing: return zero length array or empty collection instead of null
Finally for exception design, throw exceptions to indicate exceptional conditions and don’t force clients to use exceptions for control flow, favor unchecked exceptions and include failure capture information in exceptions
This presentation is available on InfoQ at http://www.infoq.com/presentations/effective-api-design