What makes a Good API?
- Easy to learn and use.
- Hard to misuse.
- Easy to read and maintain.
- Easy to evolve and scale.
- Satisfies requirements.
Single page specs
- Easy to modify, refactor might take just 10 minutes.
- Easy to have multiple specs and dispose off useless ones without much pain to yourself.
- Start before specs, flush out broken implementations before going into details.
- Can’t please everyone? Aim to displease everyone equally.
- Everyone should be happy enough though.
- Mistakes are fine, will be covered up once API evolves.
Do it well
- Come up with good names, let API talk to the customer. e.g.- getStatus() instead of httpRequestStatusReturned().
- API is a language, ensure consistency and symmetry in naming. That means, same word means same thing throughout the API.
- When in doubt, leave it out.
- Avoid bulk, sell concepts. E.g.-
HashSet are implementations of
Set interface in
java.util.collections, each of these teach a new concept with the same functionality.
- Consumer should learn a lot rather than do a lot.
- All user should know is
getHash() returns a unique integer for unique input. This allows you evolve your function in future without confusing user.
- Make classes, members as private as possible.
- Multiple modules over one big module. Split modules in a way that makes sense.
- Allow modules to be used, tested, debugged independently.
Documentation is a religion
- Document each public or protected member. Remember - size of block is not as good as size of block in bytes
- Each method should have preconditions, postconditions, connections, side-effects and parameters well documented.
- A slow API is better than a broken API. A good balance is required.
- Good design usually comes with a good performance.
- Mimic the core APIs and patterns in the platform. Makes easy to onboard consumers.
- Making classes immutable ensures they are thread safe and resuable. One drawback is separate object for each value.
- Reduce space usage for mutable objects.
- Name methods based on the first important thing they do.
- A method does one thing at a time. User doesn’t expect
boolean isSet() to set an unset variable and return True, it should just validate condition.
- Consistent return types. For
int getOutput() do not return
null for an empty output, instead return an empty int array.
comments powered by
- Programmatic access to all data in string form. User’s shouldn’t be parsing a string for information. E.g.- Providing an implementation of
- Cut-paste makes code error prone.
- Because you can, doesn’t mean you should.
- Use appropriate input parameter and return types.
- Don’t use string as data types, make a string into a constant and leave it there. Simplest situation would be to use a boolean instead of string “Yes/No”.
- Consistent parameter ordering. In
java.util.collections first parameter is always the collection to be queried or modified.