am a big fan of objects. It's so convenient to work with programming entities that you can ask to do something and they just do it. The shift that we developers have made from procedural style to OO style allows us to express ideas in much richer ways than were possible using procedural methods. Knowing how to identify areas where a new object can be introduced to simplify the code in your application is a talent that many spend years improving (I can't say perfect, because software development is truly an evolutionary process).
How many times in your applications do you write logic that deals with ranges of values? For example, consider an order entry system that allows "special" orders to be processed only on certain weekdaysand then only between certain hours. Systems such as this make heavy use of range checks to ensure that accepted orders meet validity constraints. It's not uncommon to see code such as this, which is an NUnit test that checks whether a date lies within a specified range:
public void ShouldBeAbleToSeeIfDateExistsInRange()
DateTime startOfJanuary2005 = new
DateTime endOfJanuary2005 = new
DateTime middleOfJanuary2005 = new
DateTime startOfFebruary2005 = new
middleOfJanuary2005 <= endOfJanuary2005);
startOfFebruary2005 <= endOfJanuary2005);
Often you'll find this type of range-checking code scattered throughout multiple parts of an application. Of course, these checks are usually not localized to one specific type; sometimes you may want to perform range checks on types other than dates. In the context of an order entry application, there may be times when you want to calculate an order discount based on the product amount purchased in a particular order. The following code shows a test for a class that encapsulates applicability for discounts.
public void ShouldTestForEligibilityOfDiscount()
IDiscount between100And300DollarDiscount =
new DiscountWithoutRange(100, 300, .10m);
The test is fairly self-explanatory. After creating a DiscountWithoutGenerics object, you can ask if it can be applied to a particular order amount. Listing 1
shows the full implementation of the DiscountWithoutGenerics class. Here's the code that actually performs the range check:
return orderAmount >= eligibleAmountStart &&
orderAmount <= eligibleAmountEnd;
Notice that other than the type (Decimal vs. DateTime) the logic for determining whether a value exists within a range is the same as the date example; in other words, it answers the question: "Does the value I care about fall between the starting and ending values of the range?"