Java 8/9 Best Practices — Part-1 (Static Factory Methods)
Join the DZone community and get the full member experience.
Join For FreeShould Consider Static Factory Methods for Creating Objects
There are various ways to create the objects in java, In a traditional way for the class to allow a client to create an instance is to provide the public default constructor. However, there is another way to create an instance of the Class. A class can provide a static public method which is a static method that returns the instance of the class. Let's see the example
public static Boolean valueOf(boolean a){
return a ? Boolean.TRUE : Boolean.FALSE;
}
There are various advantages and disadvantages to consider Static Methods -
Advantages
- Static Methods have a name
- Not required to create an object every time it gets invoked
- They can return an object of any subtype of their return type
- Class of the returned object can vary from call to call as a function of the input parameters
- Class of the returned object need not exist when the class containing the method is written
Limitations
- A class without public or protected constructor can not be sub-classed if we only expose static Method for object creation
- It could be difficult for the programmer to find the method where the object is being created unlike a constructor
Some common names for static factory methods
xxxxxxxxxx
Date d = Date.from (instance); //from
Set<Status> statuses = EnumSet.of(INITIATED, INPROGRESS,COMPLETED);//Use of Of
String str1 = String.valueOf(Integer.MAX_VALUE); // use of valueOf
Object newArray = Array.newInstance(classObject, length) // use of newInstance
BufferedReader br = Files.newBufferedReader(path);//use of newType
Both Static factory methods and public constructors both have their users. Static factories are preferable, so avoid the defining public constructor and think if Static factories can be used.
Ref - Effective Java - Third Edition by Joshua Bloch
Opinions expressed by DZone contributors are their own.
Comments