![](http://imgdetail.ebookreading.net/software_development/33/9780470596906/9780470596906__stephens-c-programming__9780470596906__bg14a.png)
264
LESSON 22 Preventing Bugs
// Calculate the average.
decimal averageSalary = AverageSalary(salaries);
// Display the result.
averageTextBox.Text = averageSalary.ToString(“C”);
}
catch (Exception ex)
{
averageTextBox.Clear();
MessageBox.Show(ex.Message);
}
}
Again a real program shouldn’t let the user enter salaries as string like this because
the user could enter invalid values.
Make the
AverageSalary method validate its inputs by asserting that the array has a reason-
able number of elements and that the salaries are reasonable. (Assume you’re not working on
Wall Street so salaries are at least $10,000 and less than $1 million.) Also validate the average.
1. You can use code similar to the following:
// Calculate the average of this array of salaries.
private decimal AverageSalary(decimal[] salaries)
{
// Sanity checks.
if (salaries.Length < 1)
{
throw new ArgumentOutOfRangeException(“salaries”,
“AverageSalary method cannot calculate average “ +
“salary for an empty array.”);
}
Debug.Assert(salaries.Length < 100, “Too many salaries.”);
for (int i = 0; i < salaries.Length; i++)
{
Debug.Assert(salaries[i] >= 10000, “Salary is too small.”);
Debug.Assert(salaries[i] < 1000000, “Salary is too big.”);
}
// Calculate the result.
decimal total = 0;
for (int i = 0; i < salaries.Length; i++)
{
total += salaries[i];
}
decimal result = total / salaries.Length;
// Validate the result.
Debug.Assert(result >= 10000, “Average salary is too small.”);
Debug.Assert(result < 1000000, “Average salary is too big.”);
return result;
}
596906c22.indd 264 4/7/10 12:33:39 PM