The coupling of the class under test

In a world of cohesive classes, we combine different classes to build large behaviors. But doing so may lead to a highly coupled design. Excessive coupling may harm evolution, as changes in one class may propagate to other classes in ways that are not clear. Therefore, we should strive for classes that are coupled as little as possible.

Your test code can help you detect highly coupled classes:

  • If the production class requires you to instantiate many dependencies in your test code, this may be a sign. Consider redesigning the class. There are different refactoring strategies you can employ. Maybe the large behavior that the class implements can be broken into two steps.
    • Sometimes coupling is unavoidable, and the best we can do is manage it better. Breaking a class enables developers to test it more easily. I will give more concrete examples of such cases.
  • Another sign is if you observe a test failing in class ATest (supposedly testing the behavior of class A), but when you debug it, you find the problem in class B. This is a clear issue with dependencies: a problem in class B somehow leaked to class A. It is time to re-evaluate how these classes are coupled and how they interact and see if such leakages can be prevented in future versions of the system.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *