Are static methods a DI anti-pattern?

匆匆过客 提交于 2019-12-02 17:05:32
Louis Wasserman

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!