A common scenario that occurs frequenfly in programming is that of enforcing constraints on a value type, such as to be within a valid range. This is one of those cases where, typically, programmers end up reinventing the wheel each time because a truly general-purpose and reusable solution is not well known. Policy-driven design easily provides a solution to this problem, as it does many others where customizable type behavior is desirable. In this article, I present a general-purpose constrained value type (see Listings 1 and 2) that can be easily modified with policies to adapt to your specific needs. A few examples of possible candidates for a cpnstrained value type include: days of the week, minutes, seconds, hours, days of the year, months, degrees of a circle, radians, strictly positive values, nonnegative values, probability, percentages, and so on. For example, here I define an integer value type that represents a base 60 number and throws an exception if ever assigned a value out of the range [0..59].
展开▼