What would you expect the code to do?

Writing quality code is about satisfying the expectations of the reader. And the reader might be yourself a couple of months later.

Let me tell you a mistake a made recently. I was test-driving a few classes and one collaborator was a stack. But I only needed the stack to give me the last two items pushed on top of it.  So I ended up with a function like this:

  1. function pop(numberOfItems){
  2. // ... some code dealing with border cases...
  3. // and the happy path:
  4. return [items[len -1], items[len -2]];
  5. }

And everything went well. The stack was good enough for the object using it.
After a few months I needed to use the stack again but I forgot about its internals. I was writing some tests for a new class also depending on a stack. As the stack was already tested, I stubbed out the "pop" method in the new test pretending it could give me the last 3 items on the stack. The unit tests passed and my new class was working fine with the stack. However, it didn't work into production. Lesson:
Although TDD encourages you write only the smallest amount of code necessary to make the test pass, you should implement all the behavior a method is expected to have when someone reads its signature.

In one way or another I was coupling the stack to the class using it. But APIs should always tell the truth. Classes and methods should do what their name say without the need to know how other artifacts consume them.


Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.