Cohesion is about a module, a class, a method, or any element in your architecture having only a single responsibility. Classes with multiple responsibilities are naturally more complex and harder to comprehend than classes with fewer responsibilities. So, strive for classes and methods that do one thing. Defining what a single responsibility means is tricky and highly context-dependent. Nevertheless, sometimes it can be easy to detect multiple responsibilities in a single element, such as a method that calculates a specific tax and updates the values of all its invoices.
Let’s give you some ideas about what you can observe in a test. Note that these tips are symptoms or indications that something may be wrong with the production code. It is up to you to make the final decision. Also, note that these tips are solely based on my experience as a developer and are not scientifically validated:
- Non-cohesive classes have very large test suites. They contain a lot of behavior that needs to be tested. Pay attention to the number of tests you write for a single class and/or method. If the number of tests grows beyond what you consider reasonable, maybe it is time to re-evaluate the responsibilities of that class or method. A common refactoring strategy is to break the class in two.
- Non-cohesive classes have test suites that never stop growing. You expect the class to reach a more stable status at some point. However, if you notice that you are always going back to the same test class and adding new tests, this may be a bad design. It is usually related to the lack of a decent abstraction.
- A class that never stops growing breaks both the Single Responsibility (SRP) and the Open Closed (OCP) principles from the SOLID guidelines. A common refactoring strategy is to create an abstraction to represent the different roles and move each calculation rule to its own class. Google the Strategy design pattern to see code examples.
Leave a Reply