Are static methods a DI anti-pattern? Are static methods a DI anti-pattern? java java

Are static methods a DI anti-pattern?


Static methods are appropriate for things that don't have associated state. Some factory methods, "purely functional" methods like Math.sin, and the like are all perfectly acceptable static methods. java.lang.Math and java.util.Collections have many fine examples of perfectly acceptable static methods.

Fortunately, these methods have no need for dependency injection, or to interact with such things; they're not unusually difficult to test. They don't have dependencies that would need mocking or anything.

On the other hand, static state, or static methods with associated static state, are utterly evil. That is an anti-pattern.

It frequently helps to define a method as being non-stateful (and therefore a legitimate static method) if, and only if, it always returns equivalent output on equivalent inputs. This makes it clear that e.g. database queries and filesystem I/O makes methods stateful, because their outputs will vary depending on what's in the filesystem or the database.


Non-trivial static methods are not compatible with dependency injection. Simply make them instance methods of singletons.


I'll rephrase your question as "How do I distinguish between when a java method should be static and when it shouldn't, when I am using dependency injection?"

In my opinion distinction should not be done purely based on whether is stateful or not, but rather whether you might want to mock the method in a test or not.I am aware that newer BDD testing framworks like Mockito are fully capable of mocking static methods, but doing so comes at significant performance cost.