6.3.2 Scoping the Range class
First we??™ll decide (broadly) what we want the type to do, as well as what it doesn??™t need
to be able to do. When developing the class, I applied test-driven development to work
out what I wanted. However, the frequent iterative nature of test-driven development
(TDD) doesn??™t work as well in a book as it does in reality, so I??™ll just lay down the
requirements to start with:
?– A range is defined by a start value and an end value (of the same type, the ???element
type???).
?– We must be able to compare one value of the element type with another.
7 http://pobox.com/~skeet/csharp/miscutil
175 Real-life example: iterating over ranges
?– We want to be able to find out whether a particular value is within the range.
?– We want to be able to iterate through the range easily.
The last point is obviously the most important one for this chapter, but the others
shape the fundamental decisions and ask further questions. In particular, it seems
obvious that this should use generics, but should we allow any type to be used for the
bounds of the range, using an appropriate IComparer, or should we only allow types
that implement IComparable
, where T is the same type? When we??™re iterating, how
do we move from one value to another? Should we always have to be able to iterate
over a range, even if we??™re only interested in the other aspects? Should we be able to
have a ???reverse??? range (in other words, one with a start that is greater than the end,
and therefore counts down rather than up)? Should the start and end points be exclusive
or inclusive?
All of these are important questions, and the normal answers would promote flexibility
and usefulness of the type??”but our overriding priority here is to keep things
simple.
Pages:
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350