A Spectrum of Complexity in Class Design

Todd Ditchendorf pointed out a disagreement between Martin Fowler and Elliott Rusty Harold on class design. Fowler appreciates all 78 methods in Ruby’s array class.

Much of an object’s strength lies in its behavior, not its data. If you only try to provide the minimum, you end up with multiple clients duplicating code for common cases. In cases like flatten you end up with a bunch of people writing their own recursive functions. It’s not hard, but why should they bother when it’s not that rare a case?

Harold thinks the class is too large and needs refactoring.

There’s simply no reason for 78 methods in a basic List [Array] 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.

I think Harold’s right when it comes to designing one’s own classes: make them small, focused and testable.

However, if a language has core classes like Array, I think there’s a reason to build in convenience methods so that users don’t have write them from scratch. Projects like Ruby have resources for writing optimized implementations of those methods, and testing them.

This summer I ended up writing about a dozen additional methods for the PHP libxml2 object. I can see other projects needing the same methods, and it would had been nice to have them baked into PHP.

More like this: , .