views:

40

answers:

1

Hi all,

in one of my project I have a Garage class.

This class contains many collections, like Addresses, BankAccounts, Memberships, etc.

All these collection classes have a validity. Meaning that an address can be valid in a period of time specified by a user. New addresses or bank accounts can be added, but the validity period is not allowed to overlap the validity of an other record.

So, what I did was making the Garage class an aggregate root. Addresses etc can be added via methods. Everytime a record is added, I do checks if the record to be added would overlap an other validity period that is already in the collection.

Like so:

        protected internal void AddAddress(Address address)
        {
            Check.Require(new IsUniqueValiditySpecification<Address>(
                    this.addresses.ToList()).IsSatisfiedBy(address), 
                    "The validity period intersects with the one of an existing address");

...
        }

Is that what an aggregate root is supposed to be used for? Or could I as well make the address an aggregate root and make it hold a reference to the garage. Then everytime the validity is set I could do something like:

public virtual Validity Validity
{
    get { return validity; }
    set { 
        Check.Require(new IsUniqueValiditySpecification<Address>(
                                this.garage.Addresses.ToList()).IsSatisfiedBy(this), 
                                "The validity period intersects with the one of an existing address");
        validity = value; 
    }
}

Or am I missing the whole point of aggregate roots? Could someone tell me some examples what the whole purpose of aggregate roots is anyway. Like an example that shows me what an aggregate root can accomplish compared to some standard approach. A real world example which shows what exact design problem is solved when using an aggregate root.

Thanks.

+2  A: 

Primary goal of aggregate roots is to structure Your objects and define explicit boundaries.

As I see it - one of the main benefits is that they eliminate web of references. State will always be changed through aggregate root, aggregate root is responsible for it's validity. That means - from upper levels, You need to think how to interact appropriately only with roots and You are not forced to think about inner details of them.

Is that what an aggregate root is supposed to be used for?

That's one of things AR is responsible for - to validate itself.

Or could I as well make the address an aggregate root and make it hold a reference to the garage.

Artificially creating aggregate roots ain't good idea. You should think carefully before promoting entity to aggregate root. More roots you got - more web like references You will have. If every entity will be root - You are back to relational database when You got no easy to follow hierarchy.

Arnis L.