开发者

Inject Util Class with Google Guice vs static Methods?

开发者 https://www.devze.com 2023-01-29 07:46 出处:网络
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:

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 UtilClass
{
  public static Result convert(Source src)
  {
    //Do conversion

    return result;
  }
}

My idea is to use guice to inject this Utility as Singleton like this

@Singleton
public class UtilClass
{
  public Result convert(Source src)
  {
    //Do conversion

    return result;
  }
}

Which way 开发者_运维知识库is recommended for an Application built with guice?


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


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消