Dart Inheritance: Prefer Composition over Inheritance

Dart Inheritance: Prefer Composition over Inheritance

While inheritance is a powerful concept, it's often recommended to favor composition over inheritance to achieve more flexible and maintainable code. Composition involves building classes by combining simpler classes rather than inheriting from them.


Example

// Composition example
class Engine {
  void start() {
    print('Engine started');
  }
}

class Car {
  Engine _engine = Engine();

  void startCar() {
    _engine.start();
    print('Car started');
  }
}

void main() {
  Car myCar = Car();
  myCar.startCar();
}

In this example, the Car class has a composition relationship with the Engine class. Instead of inheriting from Engine, a Car contains an instance of Engine and delegates the start functionality. This allows for better code reuse and flexibility.

When composing classes, changes in one component don't affect others as much compared to a deep inheritance hierarchy.