Constructors vs Static Factory Methods
While initializing variables in my programs, I used to use constructors a lot. Gradually I have moved to static factory methods somehow as suggested by many in stack overflow and then tried to find out proper reasons. I wanted to share my knowledge and experience on this one since long. But I had to wait till I get clarity and confidence to give some info on Static factory methods and why I prefer to chose them instead of Constructors. So I feel writing would makes sense than tweeting on this. Lets take a dig on little background for these two methods.
First of all why we use constructors in Java? Constructors allows you to initialize variables. It gives a value to our variables as soon as we create objects. The basic constraint to use Constructor is we have to use same name as class name.
Let me give a very easy instance of creating constructors.
Public class DigitalMusic
{
public String albumName;
public float albumNumber;
//Constructor
public DigitalMusic(float number, String name)
{
albumName = name;
albumNumber = number;
}
public void print()
{
//Print statements
}
}
As simple as that. Now you can initialize your variables using the constructor by passing values through instances. I want to create 2 objects and pass values to it.
Public Static void main(String args[0])
{
DigitalMusic d1 = new DigitalMusic(121897, "21");
DigitalMusic d2 = new DigitalMusic(134560, "19"); // 21 and 19 are strings here.
d1.print();
d2.print();
}
Fair enough and as a Java developer I pretty much know the use of constructors and when to use it. But as a reader I get one obvious question. When we have easily readable and understandable constructors, why do we have to go with other options like static factory methods? Yes, It is fairly reasonable question to ask. I will try to answer this in my way. Ofcourse there might be number of articles on this but knowing everything at one place could run things faster while coding.
Before going further, I want to make it clear that Static factory method has nothing to do with Factory pattern which we find in Design patterns. I was also a little confused about this until I read "Effective Java" By Joshua Bloch, a famous Googler and blogger.
Lets talk about the advantages of static factory methods.
a) Static factory method can have different names unlike constructors. So, we can name it according to our context to make it more easy while dealing it from our client classes.
b) Instantiation is of course as easy as constructors and we can do it on demand.
c) Unlike constructors we can represent the objects with the help of static factory methods.
d) We don't need to create an object each time we invoke static factory method. I personally like this aspect of static factory methods. Because there are number of times we see memory leaks because constructers are invoked number of times unnecessarily. Then we had to chose other methods which leads to number of methods like nullifying objects or careful usage of caches or in the worst case using of finalizers which I totally dislike to do. To avoid all these insidious consequences, lets avoid this situation before hand.
e) "Another useful advantage while inheriting number of classes is it allows immutable classes to use preconstructed instances, or to cache instances as they’re constructed, and dispense them repeatedly to avoid creating unnecessary duplicate objects."
f) There are times when you want to return objects of subclass type. Fortunately, this method do that for you without any pain boxing or creating another instance just for that.
These are some very handy benefits I found in my experience.
For reference some popular methods we use in this methods are : valueOf, Of, getInstance, newInstance, getType, newType..
In the same class we created before, we can create the following static factory method which I want to show how to use in the presence of constructors. For suppose, presume we used private constructor which is not reachable by subclasses.
//Static factory which initializes variables
public static DigitalMusic valueOf(float number, String name)
{
return new DigitalMusic(number, name);
}
Now it doesn't matter if you create a public or private constructer. It is reachable by every subclass in the above case. You can find out usage of some other methods.
One might ask if these are doing everything, why we constructors are popular widely? Because, Static methods has couple of drawbacks as well like every other method. I googled the same question to find it out myself. Following are the two valid reasons I found.
Disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed.
A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods which I think is not a major disadvantage which could potentially stop us.
So, Now I see we have a good scope of avoiding undesired memory leakages, coding friendly environment for client class coordination sort of things.
Thanks for time and appreciate inputs. Discussions are always a better way to share and learn.













