静态方法是 DI 反模式吗?
我是一名 Java 开发人员,开始掌握依赖注入的全部威力,我突然意识到没有办法注入静态方法.所以我开始思考:静态方法是 DI 反模式吗?
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();
}
}
...但我不是在问如何注入现有的静态方法...我是在问我是否应该完全停止编写它们,如果我的所有代码(从现在开始)都将接受这个概念DI.
...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!).
推荐答案
静态方法适用于没有关联状态的事物. 一些工厂方法,纯函数式"方法,例如 Math.sin
等都是完全可以接受的静态方法.java.lang.Math
和 java.util.Collections
有许多完全可以接受的静态方法的好例子.
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.
当且仅当它总是在等效输入上返回等效输出时,通常有助于将方法定义为无状态(因此是合法的静态方法).这清楚地表明,例如数据库查询和文件系统 I/O 使方法成为有状态的,因为它们的输出会根据文件系统或数据库中的内容而有所不同.
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.
相关文章