search
Get Started
search
Replace Constructor with Factory Method - Jetbrains Native Refactoring
zoom_in Click to enlarge

Replace Constructor with Factory Method

language

description Replace Constructor with Factory Method Overview

This refactoring replaces a public constructor with a static factory method. It is useful for creating more descriptive instantiation logic or enforcing specific object creation rules without exposing the internal constructor directly.

help Replace Constructor with Factory Method FAQ

What changes when a constructor is replaced with a Factory Method?

The class no longer exposes the public constructor as the main creation route. Instead, callers use a named static method that creates and returns the object.

Why use a Factory Method instead of calling new directly?

A method such as createFromConfig() can explain why an object is being created more clearly than a generic constructor call. It can also apply validation, choose a subtype, or enforce creation rules before returning the instance.

Does Replace Constructor with Factory Method require changing the object itself?

The refactoring mainly changes how callers instantiate the object, while the object's behavior can remain the same. The constructor can become private or otherwise hidden once all creation paths use the factory method.

Can a Factory Method return a subclass instead of the declared class?

Yes, a factory method can return a subtype when the creation rules call for one. That is one reason the pattern is useful when direct constructor calls would expose too much implementation detail.

Reviews & Comments

Write a Review

rate_review

Be the first to review

Share your thoughts with the community and help others make better decisions.

Save to your list

Save your favorites and follow how their scores change over time.

Save favorites
Track changes
Compare scores

Already have an account? Sign in

Compare Items

See how they stack up against each other

Comparing
VS
Select 1 more item to compare