Rule 1: Consider static factory methods instead of constructors
The traditional way for a class to allow a client to obtain an instance is to provide
a public constructor.
What is static factory methods?
A class can provide a public static factory method, which is simply a static method that returns an instance of the class.
Example : Below method translates a boolean primitive value into a Boolean object reference:
public static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}
Note : A static factory method is not the same as the Factory Method pattern
from Design Patterns.
A class can provide its clients with static factory methods instead of, or in
addition to, public constructors. Providing a static factory method instead of a
public constructor has both advantages and disadvantages.
Advantages of providing a static factory method instead of public constructor:
- Unlike constructors, they have names: A static factory with a well-chosen name is easier to use and the resulting client code easier to read. Bad way to use Constructor: A class can have only a single constructor with a given signature. Programmers have been known to GET AROUND THIS RESTRICTION by providing two constructors whose parameter lists differ only in the ORDER of their PARAMETERS TYPES. This is a REALLY BAD IDEA. The user of such an API will NEVER BE ABLE TO REMEMBER which constructor is which and will end up calling the WRONG ONE BY MISTAKE. People READING CODE that uses these constructors will NOT KNOW what the CODE DOES without referring to the CLASS DOCUMENTATION.
- Where to use static factory methods?- In cases where a class seems to require MULTIPLE CONSTRUCTORS with the SAME SIGNATURE, replace the constructors with static factory methods and carefully chosen names to highlight their differences.
- Unlike constructors,they are not required to create a new object each time they’re invoked. this allows immutable classes(Topic: Classes & Interface Rule-3) with pre-constructed instances. Example valueOf method illustrates this concept,it never creates a new object. Classes that do this are said to be instance-controlled.
- Also, it allows an immutable value class (Item 17) to make the guarantee that no two equal instances exist: a.equals(b) if and only if a == b . This is the basis of the Flyweight pattern.
- Unlike constructors,they can return an object of any subtype of their return type.This gives you great flexibility in choosing the class of the returned object.[In-progress]
- The class of the returned object can vary from call to call as a function of the input parameter
- fifth advantage of static factories is that the class of the returned object need not exist when the class containing the method is written.
Disadvantages of using static factory method instead of public constructor
- Classes without public or protected constructors cannot be sub-classed.
- They are hard for programmers to find.