Static Factory Methods in Java

In Java
July 19, 2023

The traditional method used to create an object from a class is by providing a public constructor. However, besides this method, there is another technique that programmers should be aware of. You can write a public static factory method for a class. This method simply returns an instance of that class.

One example of this method is present in the Boolean class (the wrapper class for boolean)

public static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}

A class can offer a static factory method instead of a public constructor. This method has certain advantages and disadvantages.

Naming Advantage

One of the advantages of static factory methods is that, unlike constructors, they have names. A class can have only one constructor with the same parameters. If the constructor’s parameters cannot clearly explain the returned object, giving a meaningful name to the static factory method will provide developers with readability. Static factory methods enhance code readability.

Cost Advantage

Another advantage of this approach is that, unlike constructors, they don’t have to create an instance of the class every time they are called. We don’t have the chance to implement mechanisms like caching when constantly generating new instances. Static factory methods can cache existing objects and reuse them. This can improve performance and reduce the cost of unnecessary object creation. (cost+)

Flexible Implementation

The static factory method allows choosing various internal implementations for creating objects in different forms. With public constructors, we cannot produce objects in a subtype or a different type. Static factory provides us with significant flexibility in this regard.

API Maintainability

Static factory methods can prevent the client from accessing the class structure directly and can offer a more stable API. This provides more flexibility in future versions and facilitates backward compatibility.”