Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject Util Class with Google Guice vs static Methods?

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?

like image 452
Dominik Obermaier Avatar asked Dec 06 '10 20:12

Dominik Obermaier


2 Answers

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

like image 62
axtavt Avatar answered Sep 24 '22 19:09

axtavt


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.

like image 23
ColinD Avatar answered Sep 24 '22 19:09

ColinD