97 Things Every Programmer Should Know

(Chris Devlin) #1

(^70) 97 Things Every Programmer Should Know


The Golden Rule of API Design .......................


Michael Feathers


APi DESiGN iS TOUGH, PARTiCULARLY iN THE LARGE. If you are designing
an API that is going to have hundreds or thousands of users, you have to think
about how you might change it in the future and whether your changes might
break client code. Beyond that, you have to think about how users of your API
affect you. If one of your API classes uses one of its own methods internally,
you have to remember that a user could subclass your class and override it, and
that could be disastrous. You wouldn’t be able to change that method because
some of your users have given it a different meaning. Your future internal
implementation choices are at the mercy of your users.


API developers solve this problem in various ways, but the easiest way is to
lock down the API. If you are working in Java, you might be tempted to make
most of your classes and methods final. In C#, you might make your classes
and methods sealed. Regardless of the language you are using, you might be
tempted to present your API through a singleton or use static factory meth-
ods to guard it from people who might override behavior and use your code
in ways that may constrain your choices later. This all seems reasonable, but
is it really?


Over the past decade, we’ve gradually realized that unit testing is an extremely
important part of practice, but that lesson has not completely permeated the
industry. The evidence is all around us. Take an arbitrary untested class that

Free download pdf