Static methods are evil


The idea behind static methods in Java is easy.

For those who don't know, a static method is a method which doesn't belong to a particular instance of the class, but it belongs to the class itself. You don't need an object implementation to use a static method. These kind of methods are often used for what are defined as "helper" methods, methods which perform small repeated tasks that are often independent from class context and hence should be performed in another class.

The advantages of static methods, however, are very little compared to the price you pay using static methods.

By using static methods, you're tightly coupling your implementation to these static methods.

Think about unit testing. Unit testing is about testing a very small unit of code, usually a class. The purpose is testing the behaviour of the class itself, and not the interactions with other units. Using mocks, you can easily simulate a desired behaviour for your dependencies in a specific test scenario. But, if you're testing some code which uses static methods, this is not easy - you may have to use specific input and then know the implementation of the static method. This not only breaks the definition of unit testing, but also requires you to change your tests if this static method implementation changes at some point.

In a world in which Inversion of Control and Dependency Injection are widely established in order to loosen coupling between modules, this is not only a bad practice, but also useless. Using a proper framework, for example Spring, you're able to inject your dependencies, and avoid to unnecessary couple implementations of unrelated logics.

There are some mocking frameworks which allow you to mock static method but, as per the boy scout rule, you should always refactor old legacy static methods into dependencies that can be injected - and then mocked when needed.