Fundamentals 6 min read

Advantages and Disadvantages of Using Static Factory Methods in Java

Static factory methods in Java offer several benefits over constructors—named creation, instance reuse, flexible return types, and the ability to vary returned subclasses based on parameters—while also presenting drawbacks such as reduced subclassability and discoverability, making them a selective alternative for object creation.

Cognitive Technology Team
Cognitive Technology Team
Cognitive Technology Team
Advantages and Disadvantages of Using Static Factory Methods in Java

When creating objects in Java, it is often advisable to prefer static factory methods over constructors.

Advantages

1. Named creation : Static factories can have descriptive names that indicate what kind of object is being created. For example, java.math.BigInteger#probablePrime conveys its purpose clearly.

2. Instance reuse : They are not required to create a new object on each call. Examples include:

public static Boolean valueOf(boolean b) { return (b ? TRUE : FALSE); }
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

These methods cache frequently used values, avoiding unnecessary object allocation.

3. Flexible return types : A static factory can return any subtype of its declared return type. For instance, java.util.List#of(E, E, ...) is implemented as:

static
List
of(E e1, E e2, E e3, E e4, E e5, E e6) {
    return ImmutableCollections.listFromTrustedArray(e1, e2, e3, e4, e5, e6);
}

The helper method listFromTrustedArray decides which concrete list class to instantiate:

static
List
listFromTrustedArray(Object... input) {
    assert input.getClass() == Object[].class;
    for (Object o : input) { Objects.requireNonNull(o); }
    return switch (input.length) {
        case 0 -> (List
) ImmutableCollections.EMPTY_LIST;
        case 1 -> (List
) new List12<>(input[0]);
        case 2 -> (List
) new List12<>(input[0], input[1]);
        default -> (List
) new ListN<>(input, false);
    };
}

4. Return type can vary with parameters : The class of the returned object may differ based on input. java.util.EnumSet.noneOf(Class elementType) returns either RegularEnumSet or JumboEnumSet depending on the enum size:

public static
> EnumSet
noneOf(Class
elementType) {
    Enum
[] universe = getUniverse(elementType);
    if (universe == null) throw new ClassCastException(elementType + " not an enum");
    if (universe.length <= 64)
        return new RegularEnumSet<>(elementType, universe);
    else
        return new JumboEnumSet<>(elementType, universe);
}

5. Returned class need not exist at compile time : Static factories can create objects whose concrete class is determined at runtime, such as java.sql.DriverManager#getConnection which uses the SPI mechanism:

ServiceLoader
loadedDrivers = ServiceLoader.load(Driver.class);

Disadvantages

The main limitation is that classes without public or protected constructors cannot be subclassed, reducing extensibility. Additionally, static factories are harder for programmers to discover because they do not appear as constructors in documentation, and unconventional names can obscure their purpose.

In summary, constructors are not obsolete, but in many typical scenarios, especially when the above advantages are valuable, static factory methods are the preferred way to create objects.

JavaObject CreationDesign PatternCode Examplestatic factory
Cognitive Technology Team
Written by

Cognitive Technology Team

Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.