Wednesday, June 5, 2013

When to use Inheritance, Composition, Interface, Aggregation

Composition

To identify composition associations, look for classes that cannot exist without other classes. Look for "wholes" and "parts". Ask, "Is this class part of another class?". The key question to ask is - Is this class destroyed when another class is destroyed?

Aggregation

The key difference between an aggregation and a composition is, in an aggregation, the part is not destroyed when the whole is destroyed. The part may be independent of the whole but the whole requires the part. For eg: A car class would require an engine class, chassis class. To identify aggregation, ask - Is this class part of another class and is it independent of the other class?

Inheritance

Inheritance provides the mechanism for new classes to be formed from the attributes and behavior of exisitng classes. Inheritance is best suited for relatively shallow class hierarchies. Use Inheritnace when:
  • The inheritance hieracrchy represents an is-a relaltionship and not a has-a(composition/aggregation) relationship.
  • The same behavior is applied to different data typoes.
  • The class hierarchy is reasonably shallow, and unlikely to become much deeper over time.

Interface

Like an inherited classm an interface provides a common specification for behavior, but, uunlike an inherited class, an interface cannot be created. The behavior has been abstracted out my any particular class and specifically implemented by all classes that need it.  Use interface inheritance when:
  • Unrelated object types need to provide the same behavior
  • Multiple inheritance is needed.
  • Inheritance is prohibited. For example C# structures cannot inherit from classes, but can implement interfaces.

No comments:

Post a Comment

Search This Blog