問題描述
我是一名 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.
這篇關于靜態方法是 DI 反模式嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!