Java

Intro to static factory methods and when should you prefer static methods over Constructors?

When Should You Prefer Static Methods Over Constructors?

The traditional way of creating an instance for a class is calling its constructor but any developer should also know about using a public static factory method to get an instance of the class.

Note that using the public static factory method is different than ’Factory pattern’ and you can read about Static factory vs Factory pattern here.

A class can provide its clients with static factory methods instead of, or in addition to, public constructors. It serves various purposes if you use it instead of using traditional constructors and has several advantages and few disadvantages when compared to constructors.

Advantages of using Static factory

1. Unlike constructors, static factory method of having names

A well-chosen name for static factory method is easier to use and will make your code easier to read. The same is not true with constructors and even though you can have multiple constructors in a class for different scenarios, still you can not name them differently as per their purpose.

For example, the BigInt class has a constructor as

constructor BigInteger(int, int, Random)

This constructor will return a BigInteger which probably will be a prime number, but this constructor name does not make that clear.

It could have been created as a static factory method named ‘probablePrime (good thing is, it was added in JAVA 4).

2. Not required to create a new object each time they’re invoked

It allows the creation of Immutable classes(An immutable object is one that will not change state after it is instantiated, The advantage of immutability comes with concurrency. By having an immutable object, one can ensure that all threads that are looking at the object will be seeing the same state, as the state of an immutable object will not change.).

 It can greatly improve performance if equivalent objects are requested often, especially if they are expensive to create. Instance control allows a class to guarantee that it is a singleton or non-instantiable or creating immutable value class

3. Static factory can return an object of any subtype of their return type

It gives us great flexibility in choosing the class of the returned object. Its advantage is that API can return objects without making their classes public which leads to  a very compact API

The Collections Framework API is much smaller than it would have been had it exported forty-five separate public classes, one for each convenience implementation.

If you use a static factory method to get an instance of a class, Client refers to the returned object by interface rather than the implementation class, which is generally good practice 

4.class of the returned object can vary from as a function of the input parameters.

As we have already discussed in point 3 a static factory can return any subtype of the declared return type. So your static factory method can return a subtype based on input taken.

In the OpenJDK implementation, EnumSet class does not have a constructor and uses a static factory method instead. 

The static factory class returns an instance of one of two subclasses, depending on the size of the underlying enum type. if it has sixty-four or fewer elements, as most enum types do, the static factories return a RegularEnumSet instance, which is backed by a single long; if the enum type has sixty-five or more elements, the factories return a JumboEnumSet instance, backed by a long array. 

But it does not bother the client calling static method to get. So even if in the future one of two subclasses is removed, code can be internally changed by the provider to return the remaining subclass type only and the client’s code will still work fine as it is totally abstracted from client code.

 5. Class of the returned object need not exist when the class containing the method is written

Such flexible static factory methods form the basis of service provider frameworks, like the Java Database Connectivity API (JDBC). A service provider framework is a system in which providers implement a service, and the system makes the implementations available to clients, decoupling the clients from the implementations

Disadvantages of using only Static Factory methods 

  1. Classes without public or protected constructors cannot be subclassed. 
  2.  Hard to find in documentation as they do not stand out in API documentation. So it can be difficult to find for a programmer how to instantiate a class that provides static factory methods instead of constructors.

Usecases for Static factory Methods

  • You can often avoid creating unnecessary objects by using static factory methods in preference to constructors on immutable classes that provide both.
    For example, the factory method Boolean.valueOf(String) is preferable to the constructor Boolean(String), which was deprecated in Java 9.
    The constructor must create a new object each time it’s called, while the factory method is never required to do so and won’t in practice


Conclusion

In summary, static factory methods do provide some advantages over constructors. And everyone programmer must know that when he should use static factory methods over creating a new constructor in the class.

Related posts
Java

How to create singleton class in Java?

Java

Static factory vs Factory pattern

Java

Introduction to JVM and its internals

Leave a Reply

Your email address will not be published. Required fields are marked *

Join The Club!

Be the first to learn about
our amazing Articles

let's Learn together