Encapsulating State Changes

Whenever it comes to determining whether a business object meets a certain state, I like to do create a property or method for this.  For instance, evaluate the property below:

public bool IsCompleted
{
    get { return this.CompletedDate != null; }
}

The IsCompleted property checks to see if a completed date, which is a nullable type, has a value specified to it.  If it does, then it's completed in the system.  This may seem like a simple thing, and not necessary.  Additionally, from an agile perspective, it may be viewed that I'm coding for a situation in the future that may or may not happen.

Though those are all valid points, I disagree.  I think this is the perfect way to encapsulate certain behavior and make object states easier to read (is it completed or not, vs. is the completed date null or not null).  Plus, it's very little code, and prevents more involved code changes by putting completion checking logic in one place.

For instance, what happens if the status of the object can be closed, and this is now considered a completed item?  Furthermore, closing an item does not mark it completed, because a closed item is not technically completed, yet it no longer needs to be visible in the system.  Imagine the following:

public bool IsCompleted
{
    get { return (this.CompletedDate != null) && (this.Status == "Completed" || this.Status == "Closed"); }
}

This change is easily encapsulated into one property.  If this logic is used 100 times in the system, my approach only requires one change, whereas if I didn't use this approach, 100 lines of code need to change.

Comments

No Comments

The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.