DEV Community

Cover image for Composition and Inheritance: From Cars to Cars
Ajisafe Oluwapelumi
Ajisafe Oluwapelumi

Posted on

Composition and Inheritance: From Cars to Cars

Hello and welcome! A while back, I tackled a real-world problem through Forage, and the company at the center was Lyft. While much of the material covered wasn't entirely new, what intrigued me were the concepts of composition and inheritance. These concepts played a central role in shaping Lyft's backend infrastructure and I thought to share my newfound knowledge with you. Stay tuned.

Composition: Assembling a Car

Let's say we are putting together a car. A car is made up of lots of different parts, and instead of making the whole car all at once, we start by making smaller pieces. Then, we fit these pieces together to build the complete car. This way of building things is called composition. It's a helpful approach because it gives our car flexibility. We can easily add or remove pieces as needed. This makes our finished car more versatile.

Let's see an example:

class Engine:
    def start(self):
        pass

class Wheels:
    def rotate(self):
        pass

class Car:
    def __init__(self, brand):
        self.brand = brand
        self.engine = Engine()
        self.wheels = Wheels()
Enter fullscreen mode Exit fullscreen mode

Here, we are defining three classes: Engine, Wheels, and Car. Engine and Wheels represent parts of a car while the Car class brings together an engine and wheels to construct a complete car.

We see that each part has its own functionality with specific responsibilities. The engine starts, the wheels rotate and the car cars (I thought that would come out right).

Inheritance: Family Traits Passed On

Inheritance is in the name, we inherit traits from our parents. Same applies here as our classes inherit characteristics from their base class. We can create new things based on existing things and pass down their characteristics. This approach makes us more efficient as we do not need to create things from the start.

Let's see an example:

class Vehicle:
    def __init__(self, brand):
        self.brand = brand

class Car(Vehicle):
    pass

# Creating an instance of Car
my_car = Car("Toyota")
print(f"My car's brand is {my_car.brand}")
Enter fullscreen mode Exit fullscreen mode

The Car class inherits the brand attribute from the Vehicle class without needing to redefine the __init__ method. The Car class inherits all attributes and methods from the Vehicle class while also retaining the ability to redefine and implement its own variations.

You could use both composition and inheritance together to get the best out of your application. If you'd like to explore how I employed both to address the Lyft challenge, you can find the code here.

If you've got stories about using composition and inheritance, I would love to hear them. Drop a comment below and share your experiences!

Top comments (0)