Microsoft 9GD00001 Computer Accessories User Manual


 
104 Microsoft Visual Studio 2010: A Beginner’s Guide
GetCheckingAccounts, which I did on purpose so that you’ll see different ways to use
loops; but this doesn’t affect the calling code because it’s encapsulated in individual
methods. The point to make here is that GetCheckingAccounts will only return Checking
class instances and GetSavingsAccounts will only return Saving class instances. The rest
of the algorithm in the ProcessPayrollForCheckingAndSavingAccounts method mirrors the
processing for Checking.
What should catch your attention is the duplication of code in the ProcessPayroll
ForCheckingAndSavingAccounts method. Although the Credit methods of Checking and
Saving should have different implementations, the code calling Credit can be the same,
eliminating duplication. Listing 4-6 shows how to take advantage of the fact that both
Checking and Saving implement the same interface, IAccount. You’ll see how to call
Credit on any IAccount-derived type with one algorithm, eliminating the duplication you
saw in Listing 4-5.
Listing 4-6 Processing payroll through the IAccount interface
C#:
public void ProcessPayrollForAllAccounts()
{
IAccount[] accounts = GetAllAccounts();
foreach (var account in accounts)
{
account.Credit(1000);
}
}
public IAccount[] GetAllAccounts()
{
IAccount[] allAccounts = new IAccount[4];
allAccounts[0] = new Checking();
allAccounts[1] = new Saving();
allAccounts[2] = new Checking();
allAccounts[3] = new Saving();
return allAccounts;
}