Static methods, singletons, and testability

As we have seen, static methods adversely affect testability. Therefore, a good rule of thumb is to avoid creating static methods whenever possible. Exceptions to this rule are utility methods, which are often not mocked. If your system has to depend on a specific static method, perhaps because it comes with the framework your software depends on, adding an abstraction on top of it—similar to what we did with the LocalDate class in the may be a good decision to facilitate testability.

The same recommendation applies when your system needs code from others or external dependencies. Again, creating layers and classes that abstract away the dependency may help you increase testability. Don’t be afraid to create these extra layers: although it may seem that they will increase the overall complexity of the design, the increased testability pays off.

Using the Singleton design pattern also harms testability. This approach ensures that there is only one instance of a class throughout the entire system. Whenever you need an instance of that class, you ask the singleton, and the singleton returns the same one. A singleton makes testing difficult because it is like having a global variable that is persistent throughout the program’s life cycle. When testing software systems that use singletons, we often have to write extra code in the test suite to reset or replace the singleton in the different test cases. Singletons also bring other disadvantages to maintainability in general. If you are not familiar with this pattern, I suggest reading about it.


Comments

Leave a Reply

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