I am a Java developer who is beginning to grasp the full power of dependency injections, and it suddenly dawned on me that there's no way to inject a static method. So it got me thinking: are static methods DI anti-patterns?
More importantly: if I were to embrace dependency injection, does this mean I need to stop coding static methods? I ask because there is no way to mock them and inject mock statics during unit tests, which is a huge turn-off for me.
Edit: I know that a common way to "wrap" and inject an existing static method is like this:
public class Foo {
public static void bar() { ... }
}
public interface FooWrapper {
public void bar();
}
public class FooWrapperImpl implements FooWrapper {
public void bar() {
return Foo.bar();
}
}
...but I'm not asking how to inject an existing static method...I'm asking if I should stop writing them altogether, if all my code (from this point forward) is going to embrace the notion of DI.
Also, I see a lot of similarly-related questions to this, but couldn't find an exact match that asked this same question. If you see that it is indeed a dupe of another question, please point it out to me and I will close this question myself (please don't just closevote it!).
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.