[ACCEPTED]-Are static methods a DI anti-pattern?-static-methods

Accepted answer
Score: 55

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

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

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

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

Score: 3

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

More Related questions