97 Things Every Programmer Should Know

(Chris Devlin) #1

Collective Wisdom from the Experts 39

the caller to have to make two separate calls” translated into “I didn’t want to
code up two separate methods.” There’s nothing fundamentally wrong with
convenience if it’s intended to be the antidote to tediousness, clunkiness, or
awkwardness. However, if we think a bit more carefully about it, the antidote
to those symptoms is efficiency, consistency, and elegance, not necessarily
convenience. APIs are supposed to hide underlying complexity, so we can real-
istically expect good API design to require some effort. A single large method
could certainly be more convenient to write than a well-thought-out set of
operations, but would it be easier to use?

The metaphor of API as a language can guide us toward better design decisions
in these situations. An API should provide an expressive language, which gives
the next layer above sufficient vocabulary to ask and answer useful questions.
This does not imply that it should provide exactly one method, or verb, for each
question that may be worth asking. A diverse vocabulary allows us to express
subtleties in meaning. For example, we prefer to say run instead of walk(true),
even though it could be viewed as essentially the same operation, just executed
at different speeds. A consistent and well-thought-out API vocabulary makes
for expressive and easy-to-understand code in the next layer up. More impor-
tantly, a composable vocabulary allows other programmers to use the API in
ways you may not have anticipated—a great convenience indeed for the users
of the API! Next time you are tempted to lump a few things together into one
API method, remember that the English language does not have one word
for MakeUpYourRoomBeQuietAndDoYourHomeWork, even though it would be really
convenient for such a frequently requested operation.

Free download pdf