What makes an API good
Today, once again, one of my colleagues called me to his desk and asked why the following code did not work as expected:
Debug.WriteLine("Message received: {0}", receivedMessage);
It should print out something like "Message received: Hello", right?
I've seen someone else have this problem before, and I myself did run into it.
- Look at the infotip. The first param is the message, and the second one is its category.
- Uh oh, category. How could I miss that!
I know why. He, as well as me and many other developers, expect Debug.WriteLine to work the same way as Console.WriteLine; so much that we do not notice the infotip's contents. Because Console.WriteLine is too well-known, I consider the signature of Debug.WriteLine bad design.
Good API is intuitive. The key to that is being consistent with well-known and widely used patterns. It is ideal if developers could code without looking at the documentation. Although computer is getting faster, it still takes some time to load the documentation. That reduces productivity and tests the developer's mentality. Thanks to good modern IDEs, we now less and less have to consult documentation. The usual reason I still have to look at the doc is to check out the Exceptions section. Of course, sometimes I have to consult the other information like thread safety, remarks, examples, etc. - but that is for more complex API when looking at the documentation is necessary.
I always wish that the IDE should somehow let users view exception information, at least for system types, in some form of intellisense dialog. It could do this by parsing the XML comments. The pitfall of this is that it might mislead the developer to trust that exception information which will certainly cause troubles if the method is poorly XML documented (it might still be documented well in some form else, but not XML comments). Exception documentation is just a good practice, not a contract. Java has experimented exception specification, with some benefits and some drawbacks. I am thinking of some solutions, like ExceptionAttribute, but none of them really helps.
Nevertheless, a good API should expose as much useful information as possible, in form of contracts, metadata (attributes), or at least standardized comments/documentation. Consistent style, self-documented names, commonly-used members/features emphasized. Good API + good IDE save developers' lives.
No comments:
Post a Comment