In Refactoring to Patterns, Joshua Kerievsky describes the chain contructor refactoring that can be used to remove duplicate code when a class has many contructors.
I've been coding in C# for a while now and I never figured out how to chain constructors.
As it turns out, its extremely simple. You just make the call by adding a colon and then the this keyword after the constructor parameters and pass along the parameters and default values you need.
If I use Joshua's exemple it would look like this:
public class Loan
{
private readonly float notionalField; private readonly float outstandingField;
private readonly int ratingField;
private readonly DateTime expiryField;
private readonly DateTime maturityField;
public Loan(float notional, float outstanding, int rating, DateTime expiry)
{
this.strategyField = new TermTOC();
this.notionalField = notional;
this.outstandingField = outstanding;
this.ratingField = rating;
this.expiryField = expiry;
}
public Loan(float notional, float outstanding, int rating, DateTime expiry, DateTime maturity)
{
this.strategyField = new RevolvingTermTOC();
this.notionalField = notional;
this.outstandingField = outstanding;
this.ratingField = rating;
this.expiryField = expiry;
this.maturityField = maturity;
}
public Loan(CapitalStrategy strategy, float notional, float outstanding, int rating, DateTime expiry, DateTime maturity)
{
this.strategyField = strategy;
this.notionalField = notional;
this.outstandingField = outstanding;
this.ratingField = rating;
this.expiryField = expiry;
this.maturityField = maturity;
}
}
Refactored to:
public class Loan
{
private readonly float notionalField;
private readonly float outstandingField;
private readonly int ratingField;
private readonly DateTime expiryField;
private readonly DateTime maturityField;
public Loan(float notional, float outstanding, int rating, DateTime expiry)
:this(new TermTOC(), notional, outstanding, rating, expiry, DateTime.MinValue)
{
}
public Loan(float notional, float outstanding, int rating, DateTime expiry, DateTime maturity)
:this(new RevolvingTermTOC(), notional, outstanding, rating, expiry, maturity)
{
}
public Loan(CapitalStrategy strategy, float notional, float outstanding, int rating, DateTime expiry, DateTime maturity)
{
this.strategyField = strategy;
this.notionalField = notional;
this.outstandingField = outstanding;
this.ratingField = rating;
this.expiryField = expiry;
this.maturityField = maturity;
}
}
