Classes may have several constructors: this is normal, as there may be different ways to instantiate objects of a same class.
However, when there is duplicated code across two or more contacts, maintenance problems arise.
Consider the three constructors of class \code{Loan}~\cite{Kerievsky:2004}, presented in Listing~\ref{lst:loan:constructors}, which have duplicated code.
We will use the refactoring operation named ``Chain Constructors'', whose goal is to remove duplication in constructors by making them call each other.
First, we analyze these constructors to find out which one is the ``catch-all constructor'', the one that handles all of the construction details.
It seems that it should be constructor 3, since making constructors 1 and 2 call 3 can be achieved with a minimum amount of work.
\begin{lstlisting}[caption={Constructors for class \code{Loan}},label=lst:loan:constructors,float=htbp,frame=tb]
public Loan(float notional, float outstanding, int rating, Date expiry) {
this.strategy = new TermROC();
this.notional = notional;
this.outstanding = outstanding;
this.rating = rating;
this.expiry = expiry;
}
public Loan(float notional, float outstanding, int rating, Date expiry, Date maturity) {
this.strategy = new RevolvingTermROC();
this.notional = notional;
this.outstanding = outstanding;
this.rating = rating;
this.expiry = expiry;
this.maturity = maturity;
}
public Loan(CapitalStrategy strategy, float notional, float outstanding, int rating, Date expiry, Date maturity) {
this.strategy = strategy;
this.notional = notional;
this.outstanding = outstanding;
this.rating = rating;
this.expiry = expiry;
this.maturity = maturity;
}
\end{lstlisting}
\begin{exercise}
Change constructor 1 to make it call constructor 3.
\end{exercise}
\lstset{caption={}}
\begin{solution}
\begin{java}
public Loan(float notional, float outstanding, int rating, Date expiry) {