Java News from Tuesday, December 6, 2005

Martin Fowler's a really smart guy, and he's pretty reliably right; but today he manages to get it 180° wrong. A 78 method List class is about three times as bad as a 25 method List class, not three times as good. A 12 method List class would be about twice as good. Simplicity is a virtue for both users and implementers. There's simply no reason for 78 methods in a basic List class. In fact, there's no reason for 78 public methods in any class. 78 public methods in one class is a code smell. 78 public methods make a class hard to learn, hard to use, hard to test, and hard to maintain. When a class has 78 public methods, it's time to refactor.

For instance, the Ruby List class (actually called Array but it's a list) Fowler's so fond of has a method to return the number of non-null items in the list. Now have you ever needed to do that? I haven't. Doubtless someone somewhere has occasionally needed this functionality; but one shouldn't put anything in a class just because one person needs it once a year. It's not as if figuring out the number of non-null items in a Java list is particularly hard to do in the unlikely even you need to know that.

Another example: Fowler likes the first and last methods in Ruby, but list.first() is not significantly simpler than list.get(0). list.last() is perhaps a little simpler than list.get(list.size() - 1) but only because Java stupidly indexes everything from 0 rather than 1. And how often do you actually need to get the first item in the list? Needing the last item in a list is even less common. Normally the reason we have a list in the first place is so we can iterate through it using an Iterator or foreach. More often than not no single element—first, last, or middle—is explicitly identified in the code. Java's List class does not lack any of the functionality in Ruby's. Java just factors it out into a few more classes, especially the Collections class, and skips a couple of rarely used "convenience" methods. The result is a simpler, easier-to-understand, easier-to-use, more humane API.