Core Developer Skills: Code Qualities: Testability

Recommended book

  • McConnell, Steve. Code Complete: A Practical Handbook of Software Construction. 1993.
Provide Feedback

Testing and testability are related, but not the same thing. When attempting to test a part of the system, if it is deemed to be difficult to test this can be an indicator of poor design.

Benefits

Attempting to test code offers numerous kinds of design-feedback:

  • If code is tightly coupled, then testing a single behavior of the system will require bringing up other parts of the system that are not related to the behavior but simple must be in place due to the coupling.
  • If code lacks cohesion, then the multiple responsibilities will need to be tested together, producing tests that can fail for multiple reasons.
  • If there is insufficient encapsulation in the system, then numerous negative scenarios will have to be tested. Issues which, with proper encapsulation, would be impossible for the system to have and therefore would not have to be teste for.
  • A system that lacks focus is hard to test because individual behaviors are spread throughout the system, requiring excessive work to test them.
  • Redundant code creates redundant tests, which causes problems when tests have to be maintained.

Thus, testability is a diagnostic of code quality. Bad code is hard to test. It is also an indicator of poor design, as bad designs are similarly hard to test. Because of this, considering the testability of a proposed design or code element as early as possible helps to avoid rework.

Obstacles

The best way to ensure that code is testable and, therefore, high in quality is to use Test-Driven Development.  The reason that counts as an “obstacle” is because Test-Driven Development is an hard discipline.  You can’t just start doing it and have it be helpful.  You have to put in the time to learn how to do it right.

Solutions

The upside of an hard discipline is that the investment is made early in your career and pays dividends until you retire.  Once you’ve taken the time to get good at Test-Driven Development, learning it will cease to be an obstacle.