Aggregation and composition

Types of relationship

Inheritance allowed us to define an is a type of relationship e.g. a dog is a type of animal. Aggregation and composition allow us to model a has a relationship.



Aggregation

Aggregation association or aggregation is where the relationship between objects is such that each object can be created and deleted independently of each other e.g. a project team has members. A project team would be made up of members that are employees represented by employee objects. When a project team completes a project and the project team object is destroyed the employee objects that were part of that team are unaffected.

The UML symbol to show an aggregation relationship is a line with a hollow diamond at the end. Our project team will be made up of a number of employees.



Composition

Composition defines a stricter relationship. Here one class is fully contained within another so if the container is destroyed so are all instances of the contained class e.g. A chess board is made up of 64 locations. If a board is destroyed so too will be the 64 location objects it is made up of.

The UML symbol to show a composition relationship is a line with a black diamond at the end. Our chess board will be made up of a number of locations.



Aggregation and composition example

The example below is part of a model for a conglomerate that buys and sells different companies to keep rack of their employees. In the example below there is a composition relationship between a Company and both its employees and teams. If a company were deleted then all the employees and teams would be gone too. This is because the employee and team objects are created and stored in the company object.

There is an aggregation association between a team and its members. If a team is deleted then its employee members are unaffected. You can see in the example below that after a team is deleted, it's members are unaffected.



Favour composition over inheritance

Composition should be favoured over inheritance unless the relationship is an "is a" type sort of relationship. Some objects are composed of other objects e.g. a bike object can be said to be made up of a frame object, wheel objects, gear and pedal objects and brake objects. A bike could not be thought to inherit the attributes of all of it's parts.

Composition provides greater flexibility and maintainability compared to inheritance. Inheritance can lead to tightly coupled code, where changes in the parent class can have unintended consequences for its dependant child classes.

Knowledge check


Questions:
Correct:

Question text


© All materials created by and copyright S.Goff