Inject Util Class with Google Guice vs static Meth

2019-03-19 06:55发布

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?

3条回答
劫难
2楼-- · 2019-03-19 07:33

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.

查看更多
Animai°情兽
3楼-- · 2019-03-19 07:49

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.

查看更多
家丑人穷心不美
4楼-- · 2019-03-19 07:52

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

查看更多
登录 后发表回答