Tuesday, April 28, 2009

The difference between an aggregate and a composition

Needed to jog my mind about the difference between an aggregate and a composition. Here is how I think about it….

Aggregation – Brain in a human. Human dies, so does brain.
Composition – Clothes on a human. Clothes make the human complete, but when a human dies, they are no longer needed and can be given away to another human.

Boils down to who creates the object that is being used by another object. If the object was created by the using class – it is a composition. If the object was created by some other class, then it is an aggregate.

Another way to break down a relationship into an aggregation and composition is to use the has and part-of phrases – like so:
Water is a part-of a pond (composition)
Ponds have ducks (aggregate)

Here is an example:

A university is composed of students and courses (if the university is shut down, students and courses no longer exist). Courses have (aggregate) students (If a course is cancelled, students still exist in the university and can take other courses).

Students and courses are a part-of the university. (composition)
Courses have students (aggregation)
Students have courses (aggregation)


Bottom line:

Aggregations are a weak relationship: a class cancelled doesn’t mean the student ceases to exist.
Composition are a strong relationship: courses and students cannot exist if the university is shut down.

Using the idea of who creates the objects:
1. University creates courses and students – its a composition relationship to courses and students.
2. University assigns students to courses – its an aggregation relationship.


Ideally, the relationship between students and courses would be a 2-way aggregation.


In the above example, if a student drops out, the courses don’t get cancelled, they just get notified about the fact that a student has dropped out and update their internal state to reflect that.

So what is a car?

So for the oft used example of a car – the car is truly an aggregate – as it is made up of a bunch of other parts, each of which can continue being used even if the car is sent to the junk yard and typically each of the parts are created at other factories, which are then put together (aggregated) at yet another factory to create a car.

No comments: