User Defined Types  «Prev  Next»
Lesson 8 When to use composition
Objective Describe when to use composition.

When to Use Composition

Class Relationship Implementation

In the video store example, the Customer class has attributes that are just strings and numbers. But consider the Rental class:
It should know what video has been rented and by whom. This means that each Rental object is connected to a Video object and a Customer object, like this:

Video composition diagram
Video composition diagram

Exactly how you implement this relationship will be different in C++ or in Java. Because this is the design stage, you do not yet need to consider those details.It is important to record and understand the relationships among your classes. Think back to the Check class you designed earlier. You had several choices for how to represent the amount of the check: You could use:
  1. A floating-point number, like 57.35, but then there would be round-off issues to consider
  2. An integer, like 5735, representing the number of pennies the check was for, but then you'd have to divide by 100 whenever you had calculations to do
  3. Two integers, like 57 and 35, for the dollars and the cents, but then you'd have to be careful they didn't get "out of sync." What would it mean if the dollars were 57 and the cents were -35?
Here's a solution: Use a Money class that knows all the business rules about representing money and keeps them in one place. Each Check object will be associated with a Money object.

When To Use Composition - Exercise

Click the Exercise link below to revise the course project using composition.
When To Use Composition - Exercise