Inject Util Class with Google Guice vs static Methods?

前端 未结 3 1947
小蘑菇
小蘑菇 2020-12-31 17:22

I\'m wondering if it is a good style to inject utility methods with google guice.

Let\'s say we have a Converter Utility Class:

public class UtilClas         


        
相关标签:
3条回答
  • 2020-12-31 17:27

    Personally I typically try to not let the fact my application is wired using a dependency injection framework influence the design decisions I make for my classes etc. Good design practices should dictate that. In your case it would seem your utility class has no dependency on state therefore it seems a sensible candidate to remain as static.

    Regardless of this, your utility class is not an implementation of any interface so the client code using it still has a tightly coupled dependency. With this it is difficult to see what is the benefit of using DI to inject the utility class at all, as opposed to just referencing the static class directly in your client code.

    0 讨论(0)
  • 2020-12-31 17:43

    First of all, what is your goal in injecting an instance of this utility class rather than continuing to use the static method you have? Functions with input and output and no side effects are often best as static methods. That said, maybe you want to be able to change what this method does for testing or some such. In that case, you'd generally want to have the class implement some interface that you use in client classes.

    At any rate, if UtilClass is stateless I'd just inject it not as a singleton. Injecting a non-singleton is faster than injecting a singleton. Maybe if you're going to be storing the injected instance in lots of other classes, a singleton might make sense to save space.

    0 讨论(0)
  • 2020-12-31 17:46

    It depends on the nature of your convert() method.

    If it's something

    • simple
    • deterministic (i.e. doesn't depend on additional parameters)
    • have no side effects
    • is unlikely to change
    • etc

    you can keep it as a static utility method.

    Otherwise it's a good candidate for dependecy injection (you can rename it to ConversionService to make it more clear).

    0 讨论(0)
提交回复
热议问题