Effective Java - Notes - Chapter 2 - Creating and Destroying objects
1. Consider static factory methods instead of constructors
Static factory methods are the methods which simply return an instance of the class.
public static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}Advantages:
a. They have names
Static factory methods have names, constructors do not. So it becomes easier for the user to know the purpose of these methods.
b. Objects can be cached
Unlike constructors, static factory methods can return the same objects (e.g. See Boolean class example above), which is memory efficient.
c. Static factory methods can return the subtype of their class type
With the same interface, which is a good practice.
d. They reduce the verbosity of creating parameterized instances,
Example,
Map<String, Boolean> map = new HashMap<String, Boolean>();
versus
Map<String, Boolean> map = Hashmap.newInstance();
Though after Java 1.7, this problem has been solved, you can use <> directly, e.g.,
Map<String, Boolean> map = new HashMap<>();
Disadvantages:
a. A class with only static factory methods without a constructor cannot be subclassed.
b. Static factory methods are not really distinguishable from other static methods.
4. Enforce noninstantiability with a private constructor
Often there are classes which serve as a set of static methods, e.g. java.lang.Math
These type of classes have a bad reputation, because they cannot be thought in terms of objects.
To avoid subclassing and instantiation of these classes, a private constructor can be used.
To avoid the instantiation from within the class, the private constructor can be made to throw an AssertionError() on instantiation, like this:
// Noninstantiable utility class
public class UtilityClass {
// Suppress default constructor for noninstantiability
private UtilityClass() {
throw new AssertionError();
}
... // Remainder omitted
}
Comments
Post a Comment