Wednesday, 22 August 2012

Association, Aggregation and Composition in .NET


Association is a relationship where all object have their own lifecycle and there is no owner. In simple language it’s a relationship between two classes where one class use another.

Aggregation is a specialize form of Association where all object have their own lifecycle but there is ownership and child object can not belongs to another parent object. Let’s take an example of Department and HOD(Head of Department).  Say a single HOD can not belongs to multiple departments, but if we delete the Department HOD object will not destroy. We can think about “has-a” relationship.

Composition is again specialize form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object dose not have their lifecycle and if parent object deletes all child object will also be deleted. Let’s take again an example of relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room can not belongs to two different house if we delete the house room will automatically delete. Say here I am Using University and Department. Department has no existance without Unversity. So the Lifetime of Department is controlled by the University.


.NET implementation of both composition & aggregation are pretty similar. Aggregation differs from ordinary composition in that it does not imply ownership. In composition, when the owning object is destroyed, so are the contained objects. In aggregation, this is not necessarily true. For example, a university owns various departments (e.g., chemistry), and each department has an HOD. If the university closes, the departments will no longer exist, but the HOD in those departments will continue to exist. Therefore, a University can be seen as a composition of departments, whereas departments have an aggregation of HOD.



Let’s test the same: Here I am aggregating a HOD to a Department[0] of University1. Now look at the try catch block. Here I am trying to aggregate the same to Department[0] of University2. But this time it’s throwing the error which is satisfying the condition of unique parent.