Bad Method Cohesion
25 August 2014
In a previous post, I talked about bad coupling through injecting too many dependencies into a class. Developers should also be concerned with the cohesion within individual methods. In the 1993 classic Code Complete (which is great, but a little dated), it said that a method should be under 200 lines of code (LoC). In more recent years, after test driven development methodologies have taken hold, we find that the LoC metric is not as good of an indicator as it was in the past. Therefore, methods with 200 lines are absurdly large in today's world. Large methods have the following problems:
- They likely have high cyclomatic complexity
- They often have maintainability issues
- They are often difficult to read
- They probably do more than their name implies
Just like class names should be specific and descriptive of everything it does, method names should also tell the story of everything that the method does. The more "And"s and "Or"s that should be in that name, the less cohesion that method has.
A method should do one thing and only one thing. This generally makes the methods really small. The benefits of small methods are that it:
- Improves readability
- Improves testability
- Makes it easier to have a small number of arguments
- Makes it easier to separate commands from queries (see the CQRS pattern)
- Makes it easier to not repeat yourself (see the DRY Principle)
- Makes it easier to remove redundant comments
- Makes it easier to avoid the paradigm of Structure Programming
One of the side effects of breaking down methods is that it decreases the cohesion of your classes. After you break down your methods, be sure to recheck the structure of your classes.
Breaking down methods so that they do one and only one thing is important not only at the method level, but it also affects the structure or your overall program. There are many benefits to keeping methods small whether or not you are writing unit tests.