Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

java - Are static methods a DI anti-pattern?

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!).

question from:https://stackoverflow.com/questions/9367610/are-static-methods-a-di-anti-pattern

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...