Keep Your Methods Private and your APIs Minimal

Tuesday, November 11th, 2008

I was reminded once more today just how important it is to write minimal APIs that don’t expose more than they have to. Briefly I had code like this:

 private boolean flag;

 public boolean getFlag() {
   return this.flag;
 }

  public boolean setFlag(boolean value);
    this.flag = value;
  }

Pretty boilerplate stuff, I think you’ll agree.

However I noticed that after some refactoring that merged a couple of classes I was now only calling getFoo() from within the same class (or at least I thought I was) so I marked it private. Eclipse promptly warned me that the method was unused so I deleted it. Then Eclipse warned me the field was unread. That seemed wrong so I looked closer and yep, it was a bug. The feature the flag was supposed to control was always on. During the refactoring I had failed to move the use of the flag field into the new class. I added a test to catch this, and fixed the problem.

What’s interesting about this example is that I found the bug only because I was aggressively minimizing the non-private parts of my API. The less public API a class has, the fewer places there are for bugs to hide. The less public API there is, the easier it is for analyzers–static, dynamic, and human–to detect problems.
(more…)