Use the Aggregate Design Pattern to Reduce Coupling
Despite that fact that architects and developers knows that tight coupling leads to increased complexity we on an almost daily basis experience that large object models grow out of control with performance problems and lack of transactional integrity as the practical results. There are many good reasons for this spanning from the inherent interconnected real world with few clear boundaries, insufficient programming language support for dynamic multi-object grouping and weak design practices.
To illustrate the problem think of a simple order management system built from three objects: order, orderline and item. The object model can be traversed as
order.orderLine.item. Assume now that the item price must be updated and what should happen with confirmed and delivered orders? Should their price also be changed? In most cases certainly not. To secure that rule item price is copied into orderLine together with the quantity.
Dealing with this type of problems at large leads us to a set of design heuristics that was first published by Eric Evans in his book Domain-Driven Design under the title aggregates. An aggregate is a set of objects that are defined to belong together and therefore should be handled as one unit when it comes to updates. The pattern also defines rules for how an object model is allowed to be connected where the following three are the most important:
1)External objects are only allowed to hold reference to aggregate root. 2)Aggregate members are only allowed to be accessed through the root. 3)Member objects only exist in context of the root.
Applying this rules on our simple order management system the following can be stated. Order is the root entity of the order aggregate. The aggregate has one member object orderLine. Item is the root of another aggregate. Deleting an order implies that all its orderLines are deleted within the same transaction. Item is not affected by changes to orders. Orders are not affected by changes to items.
Identifying aggregates can be a difficult design task, where refactoring and domain expertise is a must.
By Einar Landre
This work is licensed under a Creative Commons Attribution 3
Back to 97 Things Every Programmer Should Know home page