public void CheckLimitsWithinRange()
{
CheckInRange(AbsoluteMinimum, SuggestedMinimum, "absolute minimum", "suggested minimum");
CheckInRange(SuggestedMinimum, SuggestedMaximum, "suggested minimum", "suggested maximum");
CheckInRange(SuggestedMaximum, AbsoluteMaximum, "suggested maximum", "absolute maximum");
CheckInRange(AbsoluteMaximum, 9999, "absolute maximum", "9999");
}
private void CheckInRange(decimal first, decimal second, string property1, string property2)
{
if ((first < 0) || first > second)
Errors.Add(String.Format("{0} cannot be less than 0 or greater than {1}", property1, property2));
}
and compare that with
public void CheckLimitsWithinRange()
{
if ((AbsoluteMinimum < 0) || (AbsoluteMinimum > SuggestedMinimum))
Errors.Add("absolute minimum cannot be less than 0 or greater than suggested minimum");
if ((SuggestedMinimum < 0) || (SuggestedMinimum > SuggestedMaximum))
Errors.Add("suggested minimum cannot be less than 0 or greater than suggested maximum");
if ((SuggestedMaximum < 0) || (SuggestedMaximum > AbsoluteMaximum))
Errors.Add("suggested maximum cannot be less than 0 or greater than absolute maximum");
if ((AbsoluteMaximum < 0) || (AbsoluteMaximum > 9999))
Errors.Add("absolute maximum cannot be less than 0 or greater than 9999");
}
The two blocks do roughly the same validation, but in my opinion, the latter is far more readable and self-documenting than the former. Yet, I've seen many developers shy away from the easier but plainer code, because the developer instinct often compels them to. The beginner looking block of code is also more maintainable. Imagine part of the rule changes to "suggested minimum" has to be less than 75% of the "suggested maximum". The first example will require a new programmer to retrace the exact thought process of the original writer when that code was first conceived, which is more costly in terms of the time spent.
The example I gave seems pretty silly, but the underlying symptom is very common. When applied on a larger scale, the maintenance overhead is no longer measured in seconds or minutes but rather hours lost in project resources. I guess the point of this rant is that there's a fine balance between well-engineered code and over-engineered code. Not every block of code needs to match the consulting fee your client is paying. It's OK for code to look cheap sometimes.


