Is it good practice to inject variables in a Utility class? - java

I have the below Utility class in Java.
public class Utils {
private static Properties commonProps;
private Utils() {}
private static setCommonProps(Properties commonProps) {
Utils.commonProps = commonProps;
}
public static boolean staticMethod1() {
commonProps.get("xyz");
}
public static void staticMethod2() {
}
}
And we initialize "commonProps" with the help of Spring function org.springframework.beans.factory.config.MethodInvokingFactoryBean.
Is there anything wrong in this design of code? Can this have any bad effects?
Is it a good practice to have such variable initialization for Utility classes?
NOTE: Here "Properties commonProps" is just a placeholder. Any common member that need to be used in this class which has to be injected during startup.

In general, dependency injection is a good thing as it leads to better designs that are easier to test. In your particular case, you have to look at what you are trying to achieve.
It appears that you are trying to provide a single point to access properties through and add some value over the standard Java Properties API. For example, by providing a getBoolean() equivalent.
With regards to the single point of access you'll need to consider threading issues. However, as long as you can guarantee that your utility class is configured before you use its static methods you should be okay.
With regards to extending the Properties API, you might be better served using one of the existing libraries rather than incurring the cost of writing and maintaining your own. For example, I've found Apache Commons Configuration to be quite good.

Do not not have any mutability in static fields. That is an anti-pattern. Also do not inject static fields using Spring. Doing these things will make your code unwieldily to work with, and very hard to test.
You already have the ability to use #Value to inject fields with properties within beans. Although this is not dynamic but you really shouldn't have dynamic properties (although it's possible IMO it's not a good idea). Think of properties as startup constants or something. They shouldn't change.

Related

Best way to write Util Class

I'm new to Java
I want to write util classes for my own purposes such as FileUtil,DBUtil,...
But some people write all methods in util classes as static methods
class FileUtil{
public static File openFile(String path){
...
}
public static File readFile(String path){
...
}
...
}
and some write util class as singleton classes and write methods as public
class FileUtil{
private FileUtil(){}
public FileUtil getInstance(){
...
}
public File openFile(String path){
...
}
public File readFile(String path){
...
}
...
}
I want to know which is better way of doing it when it comes to memory allocation
Thanks in advance
Never write a singleton. If you really want static fields (don't) then write static. For (single implementation) utility methods there's no point in forcing an extra object on the client.
Look at the mess created by Runtime vs System despite being essentially the same thing.
Traditionally utility classes are written as classes with static methods. A private constructor that throws an exception can be added to prevent the default constructor being added, but adds extra mess to the code (though reduces documentation). Also adding an unnecessary final is common.
Single-element enums were popular for singletons (don't write singletons). Using the same arguments utility classes should be no-element enums, though that isn't popular for no obvious reason. Both single and no element enums add nonsense methods to the class.
If you really want concise code, use interfaces. You avoid having to write public every time and constants can elide the public static. This is apparently not very popular because it is possible for clients to ruin their own code by implementing the interface. See Swing.
Utilities:
Utility classes are classes that do not need any instance. They provide methods that help you to do things.
Singletons:
Singletons are instances that require to have one and only one instance. The reason for having singletons are various, maybe you need a single coordinator that should not be interferred...
FileUtil:
well the name points it out already, this class provides methods for a simplified file access...
FileManager:
this object is responsible to keep track of the integrity of the file System. Noone else is allowed to create/delete files but only the FileManger, hence FileManager would be a singleton. (Your Questions doesn't ask for a File Manager, but to make a difference to FileUtils i think it would be helpful)
Memory Usage / Clean Code
why this answer: you think you might optimize for memory but clean code points out that you should not optimize
Summary:
don't use a Singleton if you really don't have to do it. Use a plain utility class (it's by the way the thing you wanted to do).

Is "inject everything" a bad practice in Android?

Studying about dependency injection I found some approaches that suggests to inject everything and other saying that it's not necessary to do so.
In my current project, my rule of thumb regarding Dependency Injection is "if the class was created by me, I make it injectable". In other words only classes like SimpleDateFormat, ArrayList, HashMap are newables in my project. My intent doing this approach is that I can #Inject any class anywhere once calling Injector.getApplicationComponent().inject(this) in the Activity. Basically all my classes have a non-args constructor with #Inject.
I was primary using DI because I thought it will improve the performance and memory usage once the new operator is used exclusively by the Dagger generated classes. But I read a post from Dagger 1 developer saying that DI does not have impact on performance and the usage is basically to reduce boilerplate.
The first question is:
Dagger 2 does not any performance advantage in Android application?
My project is running without problems and I think the approach of "inject everything" helps organizing better, despite some drawbacks.
An example of usage of this approach is the following class:
public class TimelineEntryAdapter {
#Inject
Provider<TwitterEntry> mTwitterProvider;
#Inject
Provider<InstagramEntry> mInstagramProvider;
#Inject
Provider<FacebookEntry> mFacebookProvider;
#Inject
TimelineEntryComparator mComparator;
#Inject
public TimelineEntryAdapter() {
}
The second question is:
Is it a bad practice to inject everything in Android?
If the answer for the second question is "No", there is a better way to handle the non-args constructor to create classes? Because when I create an non-args constructor with #Inject annotation and a class need some parameters to work with, I must use setters:
public class SavelArtist {
private MusicBrainzArtist mMusicBrainzArtist;
private DiscogsArtist mDiscogsArtist;
private List<SavelTweet> mTweetList;
private SpotifyArtist mSpotifyArtist;
private List<SavelInstagram> mInstaTimeline;
private List<SavelFacebook> mFacebookTimeline;
private List<SavelRelease> mReleases;
#Inject
Provider<SavelRelease> mReleaseProvider;
#Inject
public SavelArtist() {
}
public void setMusicBrainzArtist(MusicBrainzArtist mbArtist) {
mMusicBrainzArtist = mbArtist;
}
public void setDiscogsArtist(DiscogsArtist discogsArtist) {
mDiscogsArtist = discogsArtist;
}
public void setTweetList(List<SavelTweet> tweetList) {
mTweetList = tweetList;
}
public void setSpotifyArtist(SpotifyArtist spotifyArtist) {
mSpotifyArtist = spotifyArtist;
}
public void setInstaTimeline(List<SavelInstagram> instaTimeline) {
mInstaTimeline = instaTimeline;
}
public void setFacebookTimeline(List<SavelFacebook> fbTimeline) {
mFacebookTimeline = fbTimeline;
}
All the parameters could be set on the constructor, once all are get at the same time in the flow.
Studying about dependency injection I found some approaches that suggests to inject everything and other saying that it's not necessary to do so.
The froger_mcs blog entry you quote doesn't advocate injecting everything. It quite clearly states:
The purpose of this post is to show what we can do, not what we should do.
And it goes on to state a disadvantage of injecting everything:
If you want to use Dagger 2 for almost everything in your project you will quickly see that big piece of 64k methods count limit is used by generated code for injections.
Now, on to your questions:
Dagger 2 does not any performance advantage in Android application?
While Dagger 2 offers a performance advantage over other reflection-based DI frameworks (such as Guice) it doesn't claim to offer any performance advantage over manually constructing your object graphs by calling constructors. You can inspect the generated classes yourself to see that these indeed still eventually call constructors.
Is it a bad practice to inject everything in Android?
Well let's take the following very common Android code:
Intent nextActivity = new Intent(this, NextActivity.class);
startActivity(nextActivity);
Should we extract an IntentFactory and inject this using Dagger 2 merely to avoid the new keyword here? At this point, it is easy to approach pedantry. The advice in the other answer you quoted about the difference between injectables and newables is more flexible and elegant.
Moving on to your next question:
If the answer for the second question is "No", there is a better way to handle the non-args constructor to create classes? Because when I create an non-args constructor with #Inject annotation and a class need some parameters to work with, I must use setters:
Using setters is the wrong approach for parameters. You should distinguish dependencies and parameters. Dependencies normally have the same lifecycle as the object itself. During the lifetime of the object, the methods exposed for that object may be called with different parameters.
I'm not a professional at dependency-management but I use it in my company so here's how I see it.
Inject everything is basically good. I make everything that is used somewhere else ( other modules, classes, packages ) injectable and only static things ( static classes with hidden constructor ), things that get only used internally non injectable.
What's the advantage of it?
Well The dependency system will take care of getting the instance and to discard it. It will clean up automatically. Also using scopes on the classes will enable you to make a class that always has only one instance in the whole application ( multiple threads access it) or make it reusable ( every thread that needs it get's an own instance ).
Also I think you could clean up your classes like this:
#Reusable (Maybe a good Idea?)
public class SavelArtist {
private MusicBrainzArtist mMusicBrainzArtist;
private DiscogsArtist mDiscogsArtist;
private List<SavelTweet> mTweetList;
private SpotifyArtist mSpotifyArtist;
private List<SavelInstagram> mInstaTimeline;
private List<SavelFacebook> mFacebookTimeline;
private List<SavelRelease> mReleases;
private Provider<SavelRelease> mReleaseProvider;
public SavelArtist() {
}
#Inject
public void init(Provider<SavelRelease> mReleaseProvider) {
this.mReleaseProvider = mReleaseProvider;
}
Think about always declaring the scope of the class. Is it a Singleton? Will it be reusable? This little detail can save you, once the application get's complex and big.
The advantage of using the method init to declare all injected variables is to have a clean looking code which is easy maintainable since everything injected is at this one location. But that's actually preference :)

When using static classes in java

I am not very familiar with java. I created a jersey web server. There is different functions such as startRodio(), stopRadio(), setRadioIp()... I created one RequestHandler class to handle the http requests and one other Radio class that implement them. All the properties and methods of the Radio class are static. it looks like
Radio
class Radio{
public static boolean radionOn;
public static String radioIpadress;
public static boolean startRadio(){
radioOn = true;
// some other operation
}
...
RequestHandler
classe RequestHandler {
#path(/startRodio)
.....
if (!Rodio.radioOn)
Radio.startRadio();
Is it a good architecture for my programm? is it a good practice to make all the properties and method static in this way?
I would say, that making properties static in default as you have made above is not good practice at all.
If you have only one instance of such object as Radio is, then use singleton pattern and private properties with proper getters and setters. This is generally best approach, because you separate public interface from private implementation and change in the implementation (e.g. renaming variable) would cause problems in other parts of application and need of refactoring.
Static variables should serve just for some common properties for defined type/class. You can for example count existing instances of class in static variable.
Better avoid using static variables. This is not a good practice. Static variables have global scopes which leaves you testing so hard. Also anything can be able to modify the static variables. more over, using static is not thread safety. Also you don't have control over the static variable i terms of their creation and destruction. SO its not advisable to use statics.
Just don't use static variables. It directly couples several of
your classes.
You can use singletons in place of static if you're sure that you
need only one object.
Simply spoken: don't use static.
static is an abnormality in good OO design. It leads to direct coupling between your classes. It makes it hard to later replace "implementation"; and it makes it hard to write reasonable unit tests.
Meaning: by default, you do not use static. There might be situations when it is fine to use; but the example code you are showing does not at all look like you should be using static.
Instead, you should be defining an interface that denotes the functionality of your Radio; allowing for different implementations behind that interfaces.
It depends on what are you looking for.
Lets say you are creating 4 objects of Radio.
radioOne....,radioFour...
Now if you want all Radios to start at same time, you should go for static variable because static properties are characteristics of all objects of a class. They are not exclusive to any particular object and in practice they should be assessed using class like :
Radio.radionOn=true;
and not radioOne.radioOn=true;
So, I would suggest you to make only those properties static which will be common to all objects. If all the properties will fall under that ambit,
then it would mean you want only one object for the class because all your objects would behave the same .So better to have one object . In that case go for singleton pattern for object creation.

Utility class in Spring application - should I use static methods or not?

Let's say I have a utility class DateUtil (see below). To use this method
a caller method uses DateUtils.getDateAsString(aDate). Would it be better to remove
the static modifier and make DateUtil a spring bean (see DateUtilsBean) and inject it into calling classes
or just leave it as is?
One disadvantage I can see with using static is issues around mocking, see How to mock with static methods?
public class DateUtils {
public static String getDateAsString(Date date) {
String retValue = "" // do something here using date parameter
return retValue;
}
}
Spring Bean version
#Component
public class DateUtilsBean {
public String getDateAsString(Date date) {
String retValue = "" // do something here using date parameter
return retValue;
}
}
I don't think so. A DateUtils class sounds like a pure utility class that doesn't have any side effects but just processes input parameters. That kind of functionality may as well remain in a static method. I don't think it's very likely that you'll want to mock date helper methods.
I agree with Sean Patrick Floyd.
This is my criterion: if the methods of the class do things only over the parameters they receive, with no external dependencies (database, file system, user config, other objects/beans, etc.), then I would do it with static methods, usually in a final class with a private constructor.
Otherwise, I would implement it using a Spring bean.
So, in the case that you raise, according to this criterion, I would write a class with static methods.
Regards.
It would be better to declare it as a Spring bean because the life cycle of it is then managed by Spring, and you can eventually inject dependencies, pool the object, as well as test it in a proper way, not to talk that you could use it as a regular object and pass it as parameter, redefine the method in subclasses... etc.
In short, yes it would be a better design in most cases. Nevertheless, in a case as simple as the exposed, it doesn't do a great difference.
A good answer in this comment Should I use static at all in spring singleton beans
static variable has one instance in one JVM. Singleton exists per spring context. If your application has only one context, they do the same job.
But do not mix them together. In some old projects, I see some not-pure utility class using some spring bean via ApplicationContext. It is very hard to write test case for it.

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

Categories

Resources