AlgoMaster Logo

Composing Objects Principle

Ashish

Ashish Pratap Singh

Imagine you are tasked with designing a car in a software system. Your first instinct, guided by early lessons in object-oriented programming, might be to think about what a car is. A car is a type of vehicle. An engine is a type of engine.

But how do you relate the car and the engine?

A beginner might be tempted to make the Car class inherit from the Engine class. After all, a car needs the functionality of an engine to work, right?

This model immediately feels wrong. A car is not an engine; a car has an engine. This simple distinction in language is the key to understanding one of the most powerful principles in object-oriented design: Favor Composition over Inheritance.

Inheritance creates an "is-a" relationship. Composition creates a "has-a" relationship. While inheritance is a powerful tool for creating subtypes, its misuse leads to rigid, fragile, and tangled systems.

Composition, on the other hand, allows you to build complex objects by assembling smaller, independent, and interchangeable parts—much like building with LEGO blocks.

This chapter will explore the classic debate between these two forms of code reuse, revealing why the simple act of "having" is often far more flexible and powerful than the act of "being."

1. The Lure of Inheritance (The "Is-A" Relationship)

Premium Content

This content is for premium members only.