Playing with Value Object Validation

by Scott MIllett 5. February 2011 13:55

Value objects are immutable and represent concerns in your domain that have no identity, things like Price, Currency, Money, Name, Address etc are all good candidates for value objects. Because Value objects are immutable they need to be created in a valid state, I have tended to use a Factory to ensure that Value objects were created in a valid state but lately I have been playing with code by contract style validators at construction time to ensure validity.

Here's some code to show you what I am talking about..

public class Name
    {        
        public Name(string first_name, string surname)
        {
            Check.that(first_name.is_not_empty()).on_constraint_failure(
                 () => { throw new ApplicationException("You must specify a first name."); });

            Check.that(surname.is_not_empty()).on_constraint_failure(
                 () => { throw new ApplicationException("You must specify a surname."); });

            this.first_name = first_name;
            this.surname = surname;
        }

        public string first_name { get; private set; }
        public string surname { get; private set; }        
    }

...and here are the supporting classes...

public static class StringExtensions
    {
        public static bool is_not_empty(this String string_to_check)
        {
            return !String.IsNullOrEmpty(string_to_check);
        }
    }

    public class CheckConstraint
    {
        private readonly bool _assertion;

        public CheckConstraint(bool assertion)
        {
            _assertion = assertion;
        }

        public void on_constraint_failure(Action action_to_perform_if_check_not_satisfied)
        {
            if (!_assertion)
                action_to_perform_if_check_not_satisfied.Invoke();
        }
    }


    public sealed class Check
    {
        public static CheckConstraint that(bool assertion)
        {
            return new CheckConstraint(assertion);
        }        
    }

Not much to it at the moment but I am going to try and find some time to play around with a fluent interface for it, just for shits and giggles.

Roger and out
Scott

Tags:

Design Patterns | Value Object

Pingbacks and trackbacks (1)+

Comments are closed

About Me

Hello my name is Scott Millett, this is my blog designed to capture my thoughts on development. You can find out more info on me by checking out my linked in profile below.

View Scott Millett's profile on LinkedIn

Coming soon...

Awards

MVP Logo

ASP.NET MVP
2010-2011

Month List

Powered by BlogEngine.NET 2.0.0.36 - Eco Theme by n3o Web Designers