Static Factory Methods

Consider static factory methods instead of constructors; this is the first rule from Effective Java. This rule claimed that developers should more often consider using static factory method instead of constructors. Java constructors are the default mechanism to initialize instances. In this post, we’ll see the advantage of using static factory methods against ordinary Java constructors.

First, there’s nothing wrong with constructors.

Here are some Java examples of static factory method usage:

String number = String.valueOf(12);
String trueValue = String.valueOf(true);
Optiona<String> text = Optional.of("text");
Optional<String> empty = Optional.empty();
List<Integer> unmodifiableList = List.of(1, 2, 4);
List<Integer> integers = Collections.unmodifiableMap(1, 2, 4);

Static factory methods are a powerful alternative to constructors. Here are some of their advantages:

Here are some disadvantages:

Of course, we can implement our static factory methods.

class Person {
  private String firstName;
  private String country;
  // etc. - more attributes  
  public static Person createWithFirstName(String firstName) {
    // do some stuff with input values
    return new Person(firstName, "earth", ...);
  // etc. - more factory methods

  // private constructor
  private Person(String firstName, String country, ...) { }

  // useful method
  public String getDisplayName() { }

In this post, we presented the advantages of using static factory methods and show a few use cases to be a better alternative to Java default constructors.