Aggregation and Composition

Aggregation and Composition

One of my biggest btes noires in modeling is aggregation. It's easy to explain glibly: Aggregation is the part-of relationship. It's like saying that a car has an engine and wheels as its parts. This sounds good, but the difficult thing is considering what the difference is between aggregation and association.

In the pre-UML days, people were usually rather vague on what was aggregation and what was association. Whether vague or not, they were always inconsistent with everyone else. As a result, many modelers think that aggregation is important, although for different reasons. So the UML included aggregation, but with hardly any semantics. As Jim Rumbaugh says, "Think of it as a modeling placebo" (Rumbaugh, Jacobson, and Booch 1999).

In addition to aggregation, the UML offers a stronger variety of aggregation, called composition. With composition, the part object may belong to only one whole; further, the parts are usually expected to live and die with the whole. Usually, any deletion of the whole is considered to cascade to the parts.

This cascading delete is often considered to be a defining part of aggregation, but it is implied by any association end with a 1..1 multiplicity; if you really want to delete a Customer, for instance, you must cascade that delete to Orders (and thus to Order Lines).

Figure 6-6 shows examples of these constructs. The compositions to Point indicate that any instance of Point may be in either a Polygon or a Circle, but not both. An instance of Style, however, may be shared by many Polygons and Circles. Furthermore, this implies that deleting a Polygon would cause its associated Points to be deleted, but not the associated Style.

Figure 6-6. Aggregation and Composition

This constraintthat a Point may appear in only one Polygon or Circle at a timecould not be expressed by the multiplicities alone. It also implies that the point is a value object (see "Reference Objects and Value Objects" on page 93). You can add a 0..1 multiplicity to a composite side of the association, but often I don't bother. The black diamond says all that needs to be said.

Figure 6-7 shows another notation for composition. In this case, you put the component inside the whole. The component class's name is not bold, and you write it in the form rolename:Class name. In addition, you put the multiplicity in the top right corner. You can also use an attribute for a single-valued component.

Figure 6-7. Alternative Notation for Composition

Different composition notations work for different situations. There are a couple more, although the variety of composition notations offered by the UML does get rather overwhelming. Note that these variations can be used only for composition, not aggregation.