2.2.  Identify when and how to use composition to solve business problems

[Note]

Object composition is a way to combine simple objects or data types into more complex ones.

Composited (composed) objects are often referred to as having a "has a" relationship. A real-world example of composition may be seen in an automobile: the objects wheel, steering wheel, seat, gearbox and engine may have no functionality by themselves, but an object called automobile containing all of those objects would serve a higher function, greater than the sum of its parts.

When, in a language, objects are typed, types can often be divided into composite and noncomposite types, and composition can be regarded as a relationship between types: an object of a composite type (e.g. car) "has an" object of a simpler type (e.g. wheel).

Composition must be distinguished from subtyping, which is the process of adding detail to a general data type to create a more specific data type. For instance, cars may be a specific type of vehicle: car is a vehicle. Subtyping doesn't describe a relationship between different objects, but instead, says that objects of a type are simultaneously objects of another type.

You should prefer composition over inheritance as it is more flexible and easy to modify later. With composition, it's easy to change behavior on the fly with dependency injection or setters. Inheritance is more rigid as most languages do not allow you to derive from more than one type.

In UML, an object relationship that is formed using composition is drawn using a filled diamond. The following UML diagram illustrates the concepts of composition:

Composition in UML

In the diagram above, the battery, the door, and the engine have no meaning outside of the car, as the car cannot work without either of them, so the relationship is formed using composition.

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Free SCDJWS 5.0 Guide