Showing posts with label Domain Driven Design. Show all posts
Showing posts with label Domain Driven Design. Show all posts

Thursday, November 29, 2007

Intention-concealing interfaces: blob parameters

When someone is using your code, you want your code to be as explicit and easy to understand as possible.  This is achieved through Intention-Revealing Interfaces.  Evans describes the problems of opaque and misleading interfaces in Domain-Driven Design:

If a developer must consider the implementation of a component in order to use it, the value of encapsulation is lost.  If someone other than the original developer must infer the purpose of an object or operation based on its implementation, that new developer may infer a purpose that the operation or class fulfills only by chance.  If that was not the intent, the code may work for the moment, but the conceptual basis of the design will have been corrupted, and the two developers will be working at cross-purposes.

His recommendation is to create Intention-Revealing Interfaces:

Name classes and operations to describe their effect and purpose, without reference to the means by which they do what they promise.  This relieves the client developer of the need to understand the internals.  The name should conform to the Ubiquitous Language so that the team members can quickly infer their meaning.  Write a test for a behavior before creating it, to force your thinking into client developer mode.

Several times now I've run into blob parameters (I'm sure there are other names for them).  Blob parameters are amorphous, mystery parameters used in constructors and methods, usually of type ArrayList, HashTable, object[], or even params object[].  Here's an example:

public class OrderProcessor
{
    public void Process(object[] args)
    {
        Order order = (Order) args[0];
        Customer customer = (Customer) args[1];

        // etc.
    }
}

The intentions behind this code are good, but the results can lead to some frustrating results.  Furthermore, this pattern leads to "Intention-Concealing Interfaces", which is style completely opposite from the Intention-Revealing style Eric proposes.  Clients need to know the intimate details of the internal implementation of the component in order to use the blob parameters.

Wrong kind of extensibility

Blob parameters lead to the worst kind of coupling, beyond just "one concrete class using another concrete class".  When using blob parameters, the client gets coupled to the internal implementation of unwinding the blob.  Additionally, new client code must have intimate knowledge of the details, as the correct order of the parameters is not exposed by the blob method's interface.

When a developer needs to call the "Process" method above, they are forced to look at the internal implementation.  Hopefully they have access to the code, but otherwise they'll need to pop open Reflector to determine the correct parameters to pass in.  Instead of learning if the parameters are correct at compile-time, they have to wait until run-time.

Alternatives

Several alternatives exist before resorting to blob parameters:

  • Explicit parameters
  • Creation method
  • Factory patterns
  • IoC containers
  • Generics

Each of these alternatives can be used separately or combined together to achieve both Intention-Revealing Interfaces and simple code.

Explicit Parameters

Explicit parameters just means that members should ask explicitly what they need to operate through their signature.  The Process method would be changed to:

public class OrderProcessor
{
    public void Process(Order order, Customer customer)
    {
        // etc.
    }
}

The Process method takes exactly what components it needs to perform whatever operations it does, and clients of the OrderProcessor can deduce this simply through the method signature.

If this signature needs to change due to future requirements, you have a few choices to deal with this change:

  • Overload the method to preserve the existing signature
  • Just break the client code

People always assume it's a big deal to break client code, but in many cases, it's not.  Unless you're shipping public API libraries as part of your product, backwards compatibility is something that can be dealt with through Continuous Integration.

Creation Method/Factory Patterns/IoC Containers

When blob parameters start to invade constructors, it's a smell that you need some encapsulation around object creation.  Instead of dealing with changing requirements through blob parameters, encapsulate object creation:

public class OrderProcessor
{
    private readonly ISessionContext _context;

    public OrderProcessor() : this(ObjectFactory.GetInstance<ISessionContext>())
    {
    }

    public OrderProcessor(ISessionContext context)
    {
        _context = context;
    }
}

Originally, the ISessionContext was a hodgepodge of different object that I needed to pass in to the OrderProcessor class.  Since these dependencies became more complex, I encapsulated them into a parameter object, and introduced a factory method (the "ObjectFactory" class) to encapsulate creation.  Client code no longer needs to pass in a group of complex objects to create the OrderProcessor.

Generics

Sometimes blob parameters surface because a family of objects needs to be created or used, but all have different needs.  For example, the Command pattern that requires data to operate might look like this before generics:

public interface ICommand
{
    void Execute(object[] args);
}

public class TransferCommand : ICommand
{
    public void Execute(object[] args)
    {
        Account source = (Account) args[0];
        Account dest = (Account) args[1];
        int amount = (int) args[2];

        source.Balance -= amount;
        dest.Balance += amount;
    }
}

The ICommand interface needs to be flexible in the arguments it can pass to specific implementations.  We can use generics instead of blob parameters to accomplish the same effect:

public interface ICommand<T>
{
    void Execute(T args);
}

public struct Transaction
{
    public Account Source;
    public Account Destination;
    public int Amount;

    public Transaction(Account source, Account destination, int amount)
    {
        Source = source;
        Destination = destination;
        Amount = amount;
    }
}

public class TransferCommand : ICommand<Transaction>
{
    public void Execute(Transaction args)
    {
        Account source = args.Source;
        Account dest = args.Destination;
        int amount = args.Amount;

        source.Balance -= amount;
        dest.Balance += amount;
    }
}

Each ICommand implementation can describe its needs through the generic interface, negating the need for blob parameters.

No blobs

I've seen a lot of misleading, opaque code, but blob parameters take the prize for "Intention-Concealing Interfaces".  Instead of components being extensible, they're inflexible, brittle, and incomprehensible.  Before going down the path of creating brittle interfaces, exhaust all alternatives before doing so.  Every blob parameter I've created I rolled back later as it quickly becomes difficult to deal with.

Thursday, October 25, 2007

Specifications versus validators

Joe posed a great question on my recent entity validation post:

I question the term Validator in relation to DDD.  Since the operation of the Validator seems to be a simple predicate based on business rule shouldn't the term Specification [Evans Pg227] be used instead?

On the surface, it would seem that validation does similar actions as specifications, namely that it performs a set of boolean operations to determine if an object matches or not.

For those unfamiliar with the Specification pattern, it provides a succinct yet powerful mechanism to match an object against a simple rule.  For example, let's look at an expanded version of the original Order class on that post:

public class Order
{
    public int Id { get; set; }
    public string Customer { get; set; }
    public decimal Total { get; set; }
}

A Specification class is fairly simple, it only has one method that takes the entity as an argument:

public interface ISpecification<T>
{
    bool IsSatisfiedBy(T entity);
}

I can then create specific specifications based on user needs.  Let's say the business wants to find orders greater than a certain total, but the total can change.  Here's specification for that:

public class OrderTotalSpec : ISpecification<Order>
{
    private readonly decimal _minTotal;

    public OrderTotalSpec(decimal minTotal)
    {
        _minTotal = minTotal;
    }

    public bool IsSatisfiedBy(Order entity)
    {
        return entity.Total >= _minTotal;
    }
}

Specs by themselves aren't that useful, but combined with the Composite pattern, their usefulness really shines:

public class AndSpec<T> : ISpecification<T>
{
    private readonly List<ISpecification<T>> _augends = new List<ISpecification<T>>();

    public AndSpec(ISpecification<T> augend1, ISpecification<T> augend2) 
    {
        _augends.Add(augend1);
        _augends.Add(augend2);
    }

    public AndSpec(IEnumerable<ISpecification<T>> augends)
    {
        _augends.AddRange(augends);
    }

    public void Add(T augend)
    {
        _augends.Add(augend);
    }

    public bool IsSatisfiedBy(T entity)
    {
        bool isSatisfied = true;
        foreach (var augend in _augends)
        {
            isSatisfied &= augend.IsSatisfiedBy(entity);
        }
        return isSatisfied;
    }
}

Adding an "OrSpec" and a "NotSpec" allows me to compose some arbitrarily complex specifications, which would otherwise clutter up my repository if I had to make a single search method per combination:

OrderRepository repo = new OrderRepository();
var joesOrders = repo.FindBy(
    new AndSpec(
        new OrderTotalSpec(100.0m),
        new NameStartsWithSpec("Joe")
    ));

Given the Specification pattern (fleshed out into excruciating detail), why can't I compose validation into a set of specifications?  Let's compare and contrast the two:

Specification

  • Matches a single aspect on a single entity
  • Performs positive matching (i.e., return true if it matches)
  • Executed against a repository or a collection
  • Can be composed into an arbitrarily complex search context, where a multitude of specifications compose one search context
  • "I'm looking for something"

Validator

  • Matches as many aspects as needed on a single entity
  • Performs negative matching (i.e., returns false if it matches)
  • Executed against a single entity
  • Is intentionally not composable, a single validator object represents a single validation context
  • "I'm validating this"

So although validation and specifications are doing similar boolean operations internally, they have very different contexts on which they are applied.  Keeping these separate ensures that your validation concerns don't bleed over into your searching concerns.

Friday, October 19, 2007

Some Domain-Driven Design resources

Eric Evans' book may be the definitive resource, but there's quite a lot of supporting information on print and on the web.  For those looking to start looking at what all the DDD buzz is about, or just wanted to catch the next acronym wave, here's a list of resources for domain-driven design:

Publications

Articles/Blogs/etc

Personally, I'd start with the InfoQ article, then flush out that with the rest of the books.  For most other questions, the Yahoo group is a great resource as are plain old Google searches.

Wednesday, September 26, 2007

Driving and refining Ubiquitous Language

Scott has a nice succinct description of how Ubiquitous Language is defined.  In the original description, Eric defines Ubiquitous Language as:

A language structured around the domain model and used by all team members to connect all the activities of the team with the software.

But unless the model is created through user stories with a domain expert, the domain model doesn't necessarily represent what true concepts in the domain, but rather concepts through the emerald-colored glasses of the developer.  Language drives the model, the model can represent the language, but the model never drives the language unless through user stories.  If you find that the domain experts are using language that only exists because it exists in the software, you've made a wrong turn somewhere.

It can be easy to fall into the trap where the domain expert becomes so familiar with the software and the model, that they start defining their language from the software.  That's where the skills of the developer and modeler become even more important.  The developer needs to recognize both gaps in the language and compromises by the domain expert to fit their ideas into what they already see in the system.

So how do we make sure the language doesn't get corrupted by the model or the system?  A few things need to be in place in your team:

  • Honesty
  • Trust
  • Communication

The domain expert needs to be honest about irregularities, the developers need to trust the domain expert to be honest, and lots of communication needs to happen to build honesty and trust.

Monday, June 25, 2007

Generic Value Object Equality

I read a post from Oren the other day where he posted some code for a generic Entity base type that implemented the correct equality logic.  I realized that I've needed a generic base type for Value Objects as well.

Value Object Requirements

In the Domain Driven Design space, a Value Object:

  • Has no concept of an identity
    • Two different instances of a Value Object with the same values are considered equal
  • Describes a characteristic of another thing
  • Is immutable

Unfortunately, in nearly all cases I've run in to, we can't use Value Types in .NET to represent Value Objects.  Value Types (struct) have some size limitations (~16 bytes or less), which we run into pretty quickly.  Instead, we can create a Reference Type (class) with Value Type semantics, similar to the .NET String type.  The String type is a Reference Type, but exhibits Value Type semantics, since it is immutable.  For a Reference Type to exhibit Value Type semantics, it must:

  • Be immutable
  • Override the Equals method, to implement equality instead of identity, which is the default

Additionally, Framework Design Guidelines has some additional requirements I must meet:

  • Provide a reflexive, transitive, and symmetric implementation of Equals
  • Override GetHashCode
  • Implement IEquatable<T>
  • Override the equality operators

Generic Implementation

What I wanted was a base class that would give me all of the Framework Design Guidelines requirements as well as the Domain Driven Design requirements, without any additional logic from concrete types.  Here's what I ended up with:

public abstract class ValueObject<T> : IEquatable<T>
    where T : ValueObject<T>
{
    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        T other = obj as T;

        return Equals(other);
    }

    public override int GetHashCode()
    {
        IEnumerable<FieldInfo> fields = GetFields();

        int startValue = 17;
        int multiplier = 59;

        int hashCode = startValue;

        foreach (FieldInfo field in fields)
        {
            object value = field.GetValue(this);

            if (value != null)
                hashCode = hashCode * multiplier + value.GetHashCode();
        }

        return hashCode;
    }

    public virtual bool Equals(T other)
    {
        if (other == null)
            return false;

        Type t = GetType();
        Type otherType = other.GetType();

        if (t != otherType)
            return false;

        FieldInfo[] fields = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);

        foreach (FieldInfo field in fields)
        {
            object value1 = field.GetValue(other);
            object value2 = field.GetValue(this);

            if (value1 == null)
            {
                if (value2 != null)
                    return false;
            }
            else if (! value1.Equals(value2))
                return false;
        }

        return true;
    }

    private IEnumerable<FieldInfo> GetFields()
    {
        Type t = GetType();

        List<FieldInfo> fields = new List<FieldInfo>();

        while (t != typeof(object))
        {
            fields.AddRange(t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public));

            t = t.BaseType;
        }

        return fields;
    }

    public static bool operator ==(ValueObject<T> x, ValueObject<T> y)
    {
        return x.Equals(y);
    }

    public static bool operator !=(ValueObject<T> x, ValueObject<T> y)
    {
        return ! (x == y);
    }
}

I borrowed a little bit from the .NET ValueType base class for the implementation of Equals.  The ValueObject<T> type uses reflection to access and compare all internal fields for Equals, as well as for GetHashCode.  All implementers will need to do is to ensure that their concrete type is immutable, and they're done.

I could probably optimize the reflection calls and cache them, but this implementation is mainly for reference anyway.

The Tests

Just for completeness, I'll include the set of NUnit tests I used to write this class up.  I think the tests describe the intended behavior well enough.

[TestFixture]
public class ValueObjectTests
{
    private class Address : ValueObject<Address>
    {
        private readonly string _address1;
        private readonly string _city;
        private readonly string _state;

        public Address(string address1, string city, string state)
        {
            _address1 = address1;
            _city = city;
            _state = state;
        }

        public string Address1
        {
            get { return _address1; }
        }

        public string City
        {
            get { return _city; }
        }

        public string State
        {
            get { return _state; }
        }
    }

    private class ExpandedAddress : Address
    {
        private readonly string _address2;

        public ExpandedAddress(string address1, string address2, string city, string state)
            : base(address1, city, state)
        {
            _address2 = address2;
        }

        public string Address2
        {
            get { return _address2; }
        }

    }

    [Test]
    public void AddressEqualsWorksWithIdenticalAddresses()
    {
        Address address = new Address("Address1", "Austin", "TX");
        Address address2 = new Address("Address1", "Austin", "TX");

        Assert.IsTrue(address.Equals(address2));
    }

    [Test]
    public void AddressEqualsWorksWithNonIdenticalAddresses()
    {
        Address address = new Address("Address1", "Austin", "TX");
        Address address2 = new Address("Address2", "Austin", "TX");

        Assert.IsFalse(address.Equals(address2));
    }

    [Test]
    public void AddressEqualsWorksWithNulls()
    {
        Address address = new Address(null, "Austin", "TX");
        Address address2 = new Address("Address2", "Austin", "TX");

        Assert.IsFalse(address.Equals(address2));
    }

    [Test]
    public void AddressEqualsWorksWithNullsOnOtherObject()
    {
        Address address = new Address("Address2", "Austin", "TX");
        Address address2 = new Address("Address2", null, "TX");

        Assert.IsFalse(address.Equals(address2));
    }
    
    [Test]
    public void AddressEqualsIsReflexive()
    {
        Address address = new Address("Address1", "Austin", "TX");

        Assert.IsTrue(address.Equals(address));
    }

    [Test]
    public void AddressEqualsIsSymmetric()
    {
        Address address = new Address("Address1", "Austin", "TX");
        Address address2 = new Address("Address2", "Austin", "TX");

        Assert.IsFalse(address.Equals(address2));
        Assert.IsFalse(address2.Equals(address));
    }

    [Test]
    public void AddressEqualsIsTransitive()
    {
        Address address = new Address("Address1", "Austin", "TX");
        Address address2 = new Address("Address1", "Austin", "TX");
        Address address3 = new Address("Address1", "Austin", "TX");

        Assert.IsTrue(address.Equals(address2));
        Assert.IsTrue(address2.Equals(address3));
        Assert.IsTrue(address.Equals(address3));
    }

    [Test]
    public void AddressOperatorsWork()
    {
        Address address = new Address("Address1", "Austin", "TX");
        Address address2 = new Address("Address1", "Austin", "TX");
        Address address3 = new Address("Address2", "Austin", "TX");

        Assert.IsTrue(address == address2);
        Assert.IsTrue(address2 != address3);
    }

    [Test]
    public void DerivedTypesBehaveCorrectly()
    {
        Address address = new Address("Address1", "Austin", "TX");
        ExpandedAddress address2 = new ExpandedAddress("Address1", "Apt 123", "Austin", "TX");

        Assert.IsFalse(address.Equals(address2));
        Assert.IsFalse(address == address2);
    }

    [Test]
    public void EqualValueObjectsHaveSameHashCode()
    {
        Address address = new Address("Address1", "Austin", "TX");
        Address address2 = new Address("Address1", "Austin", "TX");

        Assert.AreEqual(address.GetHashCode(), address2.GetHashCode());
    }

    [Test]
    public void TransposedValuesGiveDifferentHashCodes()
    {
        Address address = new Address(null, "Austin", "TX");
        Address address2 = new Address("TX", "Austin", null);

        Assert.AreNotEqual(address.GetHashCode(), address2.GetHashCode());
    }

    [Test]
    public void UnequalValueObjectsHaveDifferentHashCodes()
    {
        Address address = new Address("Address1", "Austin", "TX");
        Address address2 = new Address("Address2", "Austin", "TX");

        Assert.AreNotEqual(address.GetHashCode(), address2.GetHashCode());
    }

    [Test]
    public void TransposedValuesOfFieldNamesGivesDifferentHashCodes()
    {
        Address address = new Address("_city", null, null);
        Address address2 = new Address(null, "_address1", null);

        Assert.AreNotEqual(address.GetHashCode(), address2.GetHashCode());
    }

    [Test]
    public void DerivedTypesHashCodesBehaveCorrectly()
    {
        ExpandedAddress address = new ExpandedAddress("Address99999", "Apt 123", "New Orleans", "LA");
        ExpandedAddress address2 = new ExpandedAddress("Address1", "Apt 123", "Austin", "TX");

        Assert.AreNotEqual(address.GetHashCode(), address2.GetHashCode());
    }

}

UPDATE: 6/27/07

  • Changed ValueObject<T> to implement IEquatable<T> instead of IEquatable<ValueObject<T>>
    • Equals reflects derived type instead of base type, since C# generics are not covariant (or contravariant), IEquatable<ValueObject<T>> != IEquatable<T>
  • Changed GetHashCode algorithm to use a calculated hash to cover additional test cases
    • Gather parent type field values
    • Fix transposed value bug
  • Fixed NullReferenceException bug when "other" is null for IEquatable<T>.Equals
  • Added tests to cover bugs and fixes