If you’re just starting to follow this blog series, the code to start off today is Here
With the same reasoning behind why we extracted Charge let’s work on extracting FrequentRenterPoints into a property as well.
First examine the bold/italic section of this code:
public string Statement()
{
double totalAmount = 0;
int frequentRenterPoints = 0;
string result = "Rental Record for " + Name + Environment.NewLine;
foreach (Rental rental in _rentals)
{
//add frequent renter points
frequentRenterPoints++;
//add bonus for two day release rental
if ((rental.Movie.PriceCode == Movie.NEW_RELEASE) &&
rental.DaysRented > 1) frequentRenterPoints++;
//show figures for this rental
result += "\t" + rental.Movie.Title + "\t$" +
rental.Charge.ToString() + Environment.NewLine;
totalAmount += rental.Charge;
}
//add footer lines
result += "Amount owed is $" + totalAmount.ToString() + Environment.NewLine;
result += "You earned " + frequentRenterPoints.ToString() +
" frequent renter points";
return result;
}
Basically, we’re going to extract that out into the rental object. So the code for Customer statement will look like this:
public string Statement()
{
double totalAmount = 0;
int frequentRenterPoints = 0;
string result = "Rental Record for " + Name + Environment.NewLine;
foreach (Rental rental in _rentals)
{
//add frequent renter points
frequentRenterPoints += rental.FrequentRenterPoints;
//show figures for this rental
result += "\t" + rental.Movie.Title + "\t$" +
rental.Charge.ToString() + Environment.NewLine;
totalAmount += rental.Charge;
}
//add footer lines
result += "Amount owed is $" + totalAmount.ToString() + Environment.NewLine;
result += "You earned " + frequentRenterPoints.ToString() + " frequent renter points";
return result;
}
And we’ll add the new property to Rental that looks like this:
public int FrequentRenterPoints
{
get
{
if( (Movie.PriceCode == Movie.NEW_RELEASE) && DaysRented > 1)
{
return 2;
}
else
{
return 1;
}
}
}
in the "IF" statement I’m pretty explicit with the brackets because I think it communicates better the intention of the code…
Also at this point you may be thinking, wow these articles are short and you could have just done all these steps in one example and it would have made sense.... I think fowler does this to purposefully show each individual step as an increment, where we verify with testing, reviewing our changes to ensure nothing is broken. So i'll do the same, one small change per article.