In java, It’s all about writing classes, and creating object from those classes, this process is called Instantiation. Most of new java programmer provide just a public constructor to the client in order to instantiate it, how ever there is another technique that should be a part of every programmer ’s toolkit which is static factory methods, so let’s dive in

What’s exactly a static factory method?

a public static factory method is simply just a static method that returns an instance of its class. a simple example to illustrate this is the valueOf of the Boolean class:

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

The Boolean class is the boxed primitive class forboolean, the valueOf method is used in all other boxed primitive classes like Integer.
A class can provide these static methods as an alternative or in addition to public constructors to create instances.

You are probably asking now, but why not just using the constructors ?.

In order to answer this question let’s get into some advantages of the static factory method.

Static method have names.

Usually, to get a hint about the returned object is by reading the signature of the constructor (its parameters), however using a static factory method with a well chosen name makes that a lot easier and unambiguous.

Some other uses cases need to provide two different  constructors but within the same signature, to get over this we can just change the order of one of  the constructor parameters which is really a bad idea, the client will never be able to understand or remember the difference between the two constructors, and hence, the static factory method is the best solution to such problem by giving them two well chosen names that highlight and describe the object being return.

Similar To This : Do you Think you can be a good programmer ??

The Ability to use cache

Unlike constructors, static factory methods gives you the ability to reuse existing cached objects and avoid creating duplicate objects, the Boolean.valueOf(boolean) method illustrates this technique: it never creates an object.

an other example of this advantage is the Integer.valueOf(int) method which reuse all the Integers between -127 and 127:

Integer.valueOf(5) == Integer.valueOf(5) // true
Integer.valueOf(-80) == Integer.valueOf(-80) // true
Integer.valueOf(500) == Integer.valueOf(500) // false

Returning a sub-type of the returned type


public interface Figure {
    double size();
    static Figure createCircle(double r){
        return new Circle(r);
    }
    static Figure createRect(double w,double h){
        return new Rect(w,h);
    }
}
class Circle implements Figure{
    private double r;
    public Circle(double r){
        this.r = r;
    }
    @Override
    public double size(){
        return Math.PI * r *r;
    }
}
class Rect implements Figure{
    private double w,h;
    public Rect(double w,double h){
        this.w = w;
        this.h = h;
    }
    @Override
    public double size(){
        return w*h;
    }
}

The advantage here is that the Figure interface can return objects of the Circle and Rect class knowing that they are package private. Hiding implementation classes in this fashion leads to a very compact API.
Note that since Java 8 we can use static method in interfaces, before Java 8, these static factory methods were put in a non-instantiable companion class Figures. We see this clearly in the case of the Collection interface and its companion class Collections which provide all the static factory methods for the different implementations of the Collection interface.

Handle multiple implementations of the returned object

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.

 

Conclusion:

  • Both of Constructors and static factory methods have their uses, but before jump into providing directly the public constructors for a class, you might consider static factory method first.
  • Note that static factory methods is not the same as the Factory Pattern from design patters.
  • Make sure to use well chosen names for your static factory methods if you use them

Worth noticing that this post was heavily influence by this brilliant book that I highly recommend to read.

LEAVE A REPLY

Please enter your comment!
Please enter your name here