ReSharper 2024.3 Help

Simplify object creation

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:

public class Loan { public Loan(double commitment, int riskRating, int maturity) { // implementation omitted } public Loan(double commitment, int riskRating, int maturity, DateTime expiry) { // implementation omitted } public Loan(double commitment, double outstanding, int riskRating, int maturity, DateTime expiry) { // implementation omitted } }

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 Control+Shift+R.

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:

public class LoanFactory { public static Loan CreateTermLoan(double commitment, int riskRating, int maturity) { return new Loan(commitment, riskRating, maturity); } }

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.

Last modified: 11 February 2024