Sohan's Blog

Living the Developer's Life

Excess of Private Methods Is a Code Smell

Private methods, when used meaningfully, are a great tool for writing beautiful object oriented code. But as many other things in life, excess of private methods is bad, too!

In my opinion, we use private methods to:

1.  isolate a block of code to be reused inside the class.
2.  extract code from another method for code readability.

Now, taking these two use cases in mind, here’s an easy conclusion:
The lower the ratio of public to private methods, the harder it is to write unit tests since the “units” are potentially larger.
I don’t know if there is any rule of thumb, but you will smell it when you see your unit tests require a lot of setup and assertions. Here’s a code example from the Play! framework, an MVC franework for Java developers.

You will see there are public methods with 100+ lines. I hope you agree with me:
“The code is not readable”
For the sake of readability, introducing private methods with good names would help. However, that doesn’t eliminate any of the possible code paths from the public methods. So, if you are lucky, you will see really long unit tests with complex setup conditions and mock expectations. Otherwise, there will be no tests at all! Without any tests for such long and complex methods, use them at your own risk. I won’t :(

Disclaimer: I like the play! framework a lot. However, if you take a look at their code and if you think unit testing is important, you’ll see they have a lot of rooms for improvement with simple extract method refactoring.