1.7 Composition

Introduction

In the Introduction to Object Oriented Programming, I explained that one benefit of OOP is that it allows us to conceptualize and manipulate data as we would in nature; as labels and objects. However, often things in nature can be broken down into its composite parts. For example, a Car is not just a car, it is also a collection of parts, such as a steering wheel, four wheels, an exhaust, an engine, and so on. Each of these components are objects themselves.

To replicate this idea of an "object of objects", we use the OOP principle of Composition, to define a Composite Class made up of other classes.


Composite Classes

Just as composite data types are a collection of primitive data types, so too are composite classes a collection of simpler classes. To achieve this, we simply set the attributes (not necessarily all of them) to be objects.


Composition in Python

Let's take a look at an example in Python where we define a Car as a collection of other objects.

class SteeringWheel:
    color = ""
    material = ""
    make = ""

    def turn(self, direction):
        # Some code

class Engine:
    engine_number = ""
    volume = ""

    def start(self):
       # Some code

    def stop(self):
       # Some code

class Windshield:
    thickness = ""
    area_size = ""

class Car:
    registration_number = ""
    color = ""
    steering_wheel = SteeringWheel()
    engine = Engine()
    wind_shield = Windshield()

    def __init__(self, registration_number, color):
        self.registration_number = registration_number
        self.color = color

Notice in this example, we first declare some simple classes (SteeringWheel, Engine, and Windshield), and then the composite class Car. Also notice that within the Car composite class, we have some attributes which are primitive data types (registration_number and color), and others which are Classes. To access attributes and functions of the composite objects, we use a similar syntax for accessing these of simple functions.

my_car = Car("1234", "blue")
my_car.engine.engine_number = "9876"
my_car.engine.volume = "1.6"
my_car.steering_wheel.color = "black"
my_car.engine.start()

Exercises

  1. Design a composite class for a car, which is made up of a number of components.
  2. Design a composite class for a Company, which is made up of Departments, which is made up of Employees.
  3. Design a composite class for a Course, which contains Student and Teacher objects which are children of the Person abstract class. The Course class should also contain a number of modules.

Continue on to MODULE 2: Design Principles


Comments

comments powered by Disqus