ReSharper
 
Get ReSharper
Get your hands on the new features ahead of the release by joining the Early Access Program for ReSharper 2025.1! Learn more

Simplify object creation

Last modified: 11 February 2024

Have you ever found yourself in a situation where you’ve been growing your class, adding more and more constructors all with their own configuration specifics? Have you ever wished that you could take out the object creation code into a separate class and reorganize it to be more readable?

Let’s take a look at a scenario right out of the Refactoring to Patterns book. Here we have several loan constructors all hiding the real intent in the parameters they take:

Now, let’s refactor these constructors into factory methods. To do so, we take each constructor in turn and use the Replace Constructor with Factory Method refactoring choosing in the Refactor This menu CtrlShift0R.

Replacing constructor with a factory method

Consequently, we can give the new factory method a name, but we can also specify a different class in which to put the factory method.

Replacing constructor with a factory method

What you end up with is a factory method in the LoanFactory class:

Doing this for all relevant constructors will yield a complete factory class. Note that if you put the factory methods in the originating class (for example, Loan), the corresponding constructors will turn private. But since we moved these constructors into a separate factory class, the constructors remain public.