Aggregation vs Composition

March 10th, 2008 Radim Marek

Not just while using UML, but in general object design discussions I’m often facing situation when somebody doesn’t really understand different ways how to design new objects. This blog post is my attempt to summarize the differences between aggregation and composition, and provide examples accompanied by UML diagrams. 

Answer for this confusion is in ownership. When composition is used the destruction of the object will result in destruction of it’s contained objects. When aggregation is used, this is not necessarily the case.As far as it’s only Java code concern, there is no difference what method you will use.

The significance of the need to distinguish them starts with introduction of mapping Java classes into other environments. Easiest example could be Hibernate mapping. Following POJO is not providing any information if aggregation or composition is used for homeAddress or department:

	class Employee {
		private Long id;
		private String name;
		private Department department;
		// …
		private NextOfKin nextOfKin;
		// …
	}

In this example department is obviously independent of the Employee class life cycle and therefore it’s aggregation, as the department will be there even when Employee record is not longer necessary. On other side it’s very unlikely nextOfKin will be referenced by any other component of the domain model, so it’s composition.Database design then could look like this:

Notice that department is referenced using foreign key, whereas next of kin is just component created using multiple columns from this table.When visualized using UML, only thing you have to remember is different in diamond representing association. Black diamond represent composition and white diamon aggregation. Example follows:

Hope this example will help.

Posted in design | No Comments »