A few days ago I ran into Kent Spillern’s post, Private Methods are a Code Smell. Here’s the meat of it:
Private helper methods indicate classes are doing too many things. Moving private helper methods to different classes, including creating new classes if necessary, splits the original responsibilities across multiple classes leading to simpler, better designs.
This post hit really close to home for me because I’m a heavy user of private utility methods. Splitting code up into lots of methods is a form of self-documentation that I advocate. He talks about one misuse of private methods that I don’t indulge in:
Sometimes, private methods are created to split complex logic or processes into small, easily digested pieces. Often, such private methods have gnarly dependencies because they directly access or modify internal state.
I write private methods for the reasons described in the first sentence, but I very rarely do what’s described in the second sentence — write private methods that modify the member variables in a class. Recently, though, I’ve started moving away from private methods. I don’t mind classes with lots of methods, but when you’re writing tests, it’s easiest to deal with small bits of code with known inputs and outputs.
I’ve also gotten used to frameworks like Rails and Kohana that both support the concept of helpers, which are a sort of thowback to procedural programming. I like helpers because they’re easy to test, and because you can use them in any situation you like. The more object-oriented alternative to writing helper or “util” classes is to use superclasses. Classes that share functionality extend the same superclass that contains the methods with shared functionality. This is the approach that the Spring Framework takes.
Even though I’d thought about moving away from private and protected methods, I had never really thought of them as something to be deliberately avoided, but I’m halfway along the path to being convinced.