This post originated from an RSS feed registered with Agile Buzz
by Steven E. Newton.
Original Post: On Check Constraints and Whole Value
Feed Title: Crater Moon Buzz
Feed URL: http://www.cmdev.com/buzz/blosxom.cgi?flav=rss
Feed Description: Views and experiences from the software world.
When a business object has setters for attributes that are interdependent,
one way of ensuring that those attributes maintain the required
relationship is to use check constraints on the setters. But there is a
better way, using Whole
Value.
An example first. Suppose the attributes are startDate and
endDate, where the rule is that startDate must always
be before or the same as endDate. A naive implementation, the
kind that usually comes to mind for developers used to breaking things
up into itty-bitty pices for primitives and database columns, is to have
the two separate properties on the larger object. The setters for each
attribute each check the new values against the constraint on the other
value, to ensure the business object's state is always sane.
A better way to handle this is to code the properties
in a way that eliminates the possibility of the business
object ever being in an inconsistent state. An immutable Value Object can be the solution.
A Duration object can encapsulate the startDate and endDate
into a single object with no setters, only a constructor that takes
two arguments, for the start and end dates, and does the check in the
constructor, throwing an exception if the required relationship is
violated by the supplied values. The business object that formerly had
both attributes instead has the single attribute with stters and getters
for an immutable Duration.