Hoinzey

Javascript. Kotlin. Android. Java

Java: Using static constructors over constructors

The most common way to get an instance of an object is for that class to expose a public constructor. There is another tool which I have been using more often recently however and while you won't use it as often as a public constructor you should know when it can be used. A static factory method (obviously.. Its the posts title)


You don't need to provide a public constructor or a static factory method, you can provide both. Some of the advantages to using a static factory method:

  • They can have names
  • Aren't required to create a new object

They can have names

We've all seen classes in our codebase that when you go to create a new instance it takes 8 variables that are sometimes not named so clearly. While you can debate the existence of such classes, they're out there. By using a static factory method you can make the name of what you are making obvious. Here is a simplified example.


    public class LibraryCard {

        private String name;
        private int id;
        private int bookAllowance;
        private double dailyRate;
        private double balanceDue;
        private String returnDate;
    
        public LibraryCard(String n, int id, int ba, double dr, double bd, String rd) {
            //A deliberately bad constructor
            this.name = n;
            this.id = id;
            this.bookAllowance = ba;
            this.dailyRate = dr;
            this.balanceDue = bd;
            this.returnDate = rd;
        }
        
        public static LibraryCard StudentCard(String name, int id) {
            //Preset for a student card
            return new LibraryCard(
                    name, 
                    id,
                    4,
                    0.0,
                    0.0,
                    "-");
        }
    }
                

Aren't required to create a new object

Because these static factory methods aren't required to create a new object each time they are call, you can cache expensive immutable objects or return pre-constructed objects. A good example of this is the Boolean.valueOf() method which never creates an object.


Resources

This post was written after reading Item 1 in Effective Java, third edition by Joshua Bloch. I would highly recommend this book from my reading so far and to clarify - I am in no way associated with it.