What is “Good” API Design

noyesgooddesignWhat makes a good API design? I don’t think there is a single answer to this – there are different approaches that work better in different circumstances. Here are a few examples.

Which is better – a broad or narrow API? One approach is to have a broad API – one where there are lots of methods with argument lists. Each new feature results in new API functions. Each new method gets more Javadoc (or PHPdoc or C++ doc etc) to describe how to use it and what it exists. All the method parameters can be defined clearly. These types of API also work well in IDEs with auto-completion. More code however means more to maintain.

A narrow API is one that uses name/value pairs, where the vocabulary of names is not predefined. So instead of having numerous methods, you have a small number of methods (like setProperty(String name, String value); ) but where the method has a long list of parameters.

I tend to use a broad API when there is a large user base of the API and a narrow API otherwise to keep coding and overheads lower.

In Java, should an API be defined with interfaces and then have classes implement those interfaces? Sometimes it is a good practice to define an API purely using interfaces where an application program never needs to know the exact classes selected. It’s ideal if there are multiple implementations of the API. (Each implementation inherits the interfaces.) This pattern tends to need a factory class for creating instances (the factory itself is an implementation of an interface) because the caller of the API should never know what concrete classes are being used.

How to document the API? I personally like having lots of Javadoc for each method. But I think more is worth doing. For significant APIs, I like providing documentation targeted at that operation. I typically have a User Guide and a Reference Manual. The User Guide gives example programs and says how to use the API as part of a complete solution. The Reference Manual describes every single features as a launching point into other areas of the system. I don’t use package level JavaDoc that often mainly because of the other conference.

What to document for classes and parameters? All public classes should have javadoc. The class should have Javadoc describing the purpose and references to links to requirements. Parameters documentation should include issues such as whether the parameters can be null or not.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: