link: Design Principles

Favor Composition Over Inheritance

Overview

”Favor Composition Over Inheritance” is a design principle in object-oriented programming that emphasizes the use of Composition relationships to combine behaviors at runtime rather than inheritance hierarchies, which can be rigid and less modular.

Abstract

This principle is pivotal in creating flexible software structures where objects are composed of other objects with specific behaviors, allowing for easy behavior exchange and extension without altering the object’s source code.

The principle highlights two fundamental ways of reusing functionality in object-oriented systems:

Important

  • Inheritance: An “is a” relationship that can lead to rigid class structures and complicate future changes.
  • Composition: A “has a” relationship that provides greater flexibility by assembling objects to get complex behavior.

Summary

Summary

”Favor Composition Over Inheritance” promotes designing systems that are easy to modify, extend, and test. It supports a more decoupled architecture that can evolve over time with fewer side effects, embodying the essence of flexible design in software engineering.

References

Refactoring and Design Patterns