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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With