Resume for Steven E. Newton


Readings for Code Janitors


Steven E. Newton
Crater Moon Development
© 2003-2016

On Check Constraints and Whole Value

1 Aug 2016 210 words. (1 min)

When an entity has setters for interdependent attributes, one way of maintaining the required relationship of those attributes 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 must always be before or the same as endDate. A naive implementation, the kind which may come to mind for developers used to breaking things up into itty-bitty pieces 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 entity’s state is always sane.

A better way to handle this is to code the properties to eliminate the possibility of the entity ever being in an inconsistent state. An immutable Value Object can be the solution.

A Duration type can encapsulate the startDate and endDate into a single object with no setters, only a constructor with 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 entity, formerly having both attributes instead has the single attribute as an immutable Duration.

<-Test-Defective Documentation has a Cost and a Value ->