Composition over inheritance

{{Short description|Software design pattern}}

File:UML diagram of composition over inheritance.svg

Composition over inheritance (or composite reuse principle) in object-oriented programming (OOP) is the principle that classes should favor polymorphic behavior and code reuse by their composition (by containing instances of other classes that implement the desired functionality) over inheritance from a base or parent class.{{cite book

| url = https://books.google.com/books?id=4pjbgVHzomsC&q=composite+reuse+principle&pg=PA17

| title = Java Design - Objects, UML, and Process: 1.1.5 Composite Reuse Principle (CRP)

| first = Kirk

| last = Knoernschild

| year = 2002

| publisher = Addison-Wesley Inc.

| isbn = 9780201750447

| accessdate = 2012-05-29

}} Ideally all reuse can be achieved by assembling existing components, but in practice inheritance is often needed to make new ones. Therefore inheritance and object composition typically work hand-in-hand, as discussed in the book Design Patterns (1994).{{Cite book | isbn = 0-201-63361-2 | title = Design Patterns: Elements of Reusable Object-Oriented Software | last1 = Gamma | first1 = Erich | authorlink1 = Erich Gamma | last2 = Helm | first2 = Richard | last3 = Johnson | first3 = Ralph | authorlink3 = Ralph Johnson (computer scientist) | last4 = Vlissides | first4 = John | authorlink4 = John Vlissides | year = 1994 | publisher = Addison-Wesley | page = [https://archive.org/details/designpatternsel00gamm/page/20 20] | oclc = 31171684 }}

Basics

An implementation of composition over inheritance typically begins with the creation of various interfaces representing the behaviors that the system must exhibit. Interfaces can facilitate polymorphic behavior. Classes implementing the identified interfaces are built and added to business domain classes as needed. Thus, system behaviors are realized without inheritance.

In fact, business domain classes may all be base classes without any inheritance at all. Alternative implementation of system behaviors is accomplished by providing another class that implements the desired behavior interface. A class that contains a reference to an interface can support implementations of the interface—a choice that can be delayed until runtime.

Example

=Inheritance=

An example in C++ follows:

class Object

{

public:

virtual void update() {

// no-op

}

virtual void draw() {

// no-op

}

virtual void collide(Object objects[]) {

// no-op

}

};

class Visible : public Object

{

Model* model;

public:

virtual void draw() override {

// code to draw a model at the position of this object

}

};

class Solid : public Object

{

public:

virtual void collide(Object objects[]) override {

// code to check for and react to collisions with other objects

}

};

class Movable : public Object

{

public:

virtual void update() override {

// code to update the position of this object

}

};

Then, suppose we also have these concrete classes:

  • class {{code|Player}} - which is {{code|Solid}}, {{code|Movable}} and {{code|Visible}}
  • class {{code|Cloud}} - which is {{code|Movable}} and {{code|Visible}}, but not {{code|Solid}}
  • class {{code|Building}} - which is {{code|Solid}} and {{code|Visible}}, but not {{code|Movable}}
  • class {{code|Trap}} - which is {{code|Solid}}, but neither {{code|Visible}} nor {{code|Movable}}

Note that multiple inheritance is dangerous if not implemented carefully because it can lead to the diamond problem. One solution to this is to create classes such as {{code|VisibleAndSolid}}, {{code|VisibleAndMovable}}, {{code|VisibleAndSolidAndMovable}}, etc. for every needed combination; however, this leads to a large amount of repetitive code. C++ uses virtual inheritance to solve the diamond problem of multiple inheritance.

=Composition and interfaces=

The C++ examples in this section demonstrate the principle of using composition and interfaces to achieve code reuse and polymorphism. Due to the C++ language not having a dedicated keyword to declare interfaces, the following C++ example uses inheritance from a pure abstract base class. For most purposes, this is functionally equivalent to the interfaces provided in other languages, such as Java{{cite book | title= "Effective Java: Programming Language Guide" |last=Bloch| first=Joshua| publisher=Addison-Wesley | edition=third | isbn=978-0134685991| year=2018}}{{rp|87}} and C#.{{cite book |last=Price | first=Mark J. |title=C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development: Build Applications with C#, .NET Core, Entity Framework Core, ASP.NET Core, and ML.NET Using Visual Studio Code | date=2022 | publisher= Packt |isbn= 978-1-098-12195-2}}{{rp|144}}

Introduce an abstract class named {{code|VisibilityDelegate}}, with the subclasses {{code|NotVisible}} and {{code|Visible}}, which provides a means of drawing an object:

class VisibilityDelegate

{

public:

virtual void draw() = 0;

};

class NotVisible : public VisibilityDelegate

{

public:

virtual void draw() override {

// no-op

}

};

class Visible : public VisibilityDelegate

{

public:

virtual void draw() override {

// code to draw a model at the position of this object

}

};

Introduce an abstract class named {{code|UpdateDelegate}}, with the subclasses {{code|NotMovable}} and {{code|Movable}}, which provides a means of moving an object:

class UpdateDelegate

{

public:

virtual void update() = 0;

};

class NotMovable : public UpdateDelegate

{

public:

virtual void update() override {

// no-op

}

};

class Movable : public UpdateDelegate

{

public:

virtual void update() override {

// code to update the position of this object

}

};

Introduce an abstract class named {{code|CollisionDelegate}}, with the subclasses {{code|NotSolid}} and {{code|Solid}}, which provides a means of colliding with an object:

class CollisionDelegate

{

public:

virtual void collide(Object objects[]) = 0;

};

class NotSolid : public CollisionDelegate

{

public:

virtual void collide(Object objects[]) override {

// no-op

}

};

class Solid : public CollisionDelegate

{

public:

virtual void collide(Object objects[]) override {

// code to check for and react to collisions with other objects

}

};

Finally, introduce a class named {{code|Object}} with members to control its visibility (using a {{code|VisibilityDelegate}}), movability (using an {{code|UpdateDelegate}}), and solidity (using a {{code|CollisionDelegate}}). This class has methods which delegate to its members, e.g. {{code|update()}} simply calls a method on the {{code|UpdateDelegate}}:

class Object

{

VisibilityDelegate* _v;

UpdateDelegate* _u;

CollisionDelegate* _c;

public:

Object(VisibilityDelegate* v, UpdateDelegate* u, CollisionDelegate* c)

: _v(v)

, _u(u)

, _c(c)

{}

void update() {

_u->update();

}

void draw() {

_v->draw();

}

void collide(Object objects[]) {

_c->collide(objects);

}

};

Then, concrete classes would look like:

class Player : public Object

{

public:

Player()

: Object(new Visible(), new Movable(), new Solid())

{}

// ...

};

class Smoke : public Object

{

public:

Smoke()

: Object(new Visible(), new Movable(), new NotSolid())

{}

// ...

};

Benefits

To favor composition over inheritance is a design principle that gives the design higher flexibility. It is more natural to build business-domain classes out of various components than trying to find commonality between them and creating a family tree. For example, an accelerator pedal and a steering wheel share very few common traits, yet both are vital components in a car. What they can do and how they can be used to benefit the car are easily defined. Composition also provides a more stable business domain in the long term as it is less prone to the quirks of the family members. In other words, it is better to compose what an object can do (has-a) than extend what it is (is-a).{{cite book

| last1 = Freeman

| first1 = Eric

| last2 = Robson

| first2 = Elisabeth

| last3 = Sierra

| first3 = Kathy

| last4 = Bates

| first4 = Bert

| year = 2004

| title = Head First Design Patterns

| url = https://archive.org/details/headfirstdesignp00free_633

| url-access = limited

| page = [https://archive.org/details/headfirstdesignp00free_633/page/n57 23]

| publisher = O'Reilly

| isbn = 978-0-596-00712-6

}}

Initial design is simplified by identifying system object behaviors in separate interfaces instead of creating a hierarchical relationship to distribute behaviors among business-domain classes via inheritance. This approach more easily accommodates future requirements changes that would otherwise require a complete restructuring of business-domain classes in the inheritance model. Additionally, it avoids problems often associated with relatively minor changes to an inheritance-based model that includes several generations of classes.

Composition relation is more flexible as it may be changed on runtime, while sub-typing relations are static and need recompilation in many languages.

Some languages, notably Go{{cite web |url=https://commandcenter.blogspot.com/2012/06/less-is-exponentially-more.html |title=Less is exponentially more |last1=Pike |first1=Rob |date=2012-06-25 |accessdate=2016-10-01 }} and Rust,{{Cite web |title=Characteristics of Object-Oriented Languages - The Rust Programming Language |url=https://doc.rust-lang.org/stable/book/ch17-01-what-is-oo.html#inheritance-as-a-type-system-and-as-code-sharing |access-date=2022-10-10 |website=doc.rust-lang.org}} use type composition exclusively.

Drawbacks

One common drawback of using composition instead of inheritance is that methods being provided by individual components may have to be implemented in the derived type, even if they are only forwarding methods (this is true in most programming languages, but not all; see {{section link|#Avoiding drawbacks}}). In contrast, inheritance does not require all of the base class's methods to be re-implemented within the derived class. Rather, the derived class only needs to implement (override) the methods having different behavior than the base class methods. This can require significantly less programming effort if the base class contains many methods providing default behavior and only a few of them need to be overridden within the derived class.

For example, in the C# code below, the variables and methods of the {{code|Employee}} base class are inherited by the {{code|HourlyEmployee}} and {{code|SalariedEmployee}} derived subclasses. Only the {{code|Pay()}} method needs to be implemented (specialized) by each derived subclass. The other methods are implemented by the base class itself, and are shared by all of its derived subclasses; they do not need to be re-implemented (overridden) or even mentioned in the subclass definitions.

UML class Employee.svg

// Base class

public abstract class Employee

{

// Properties

protected string Name { get; set; }

protected int ID { get; set; }

protected decimal PayRate { get; set; }

protected int HoursWorked { get; }

// Get pay for the current pay period

public abstract decimal Pay();

}

// Derived subclass

public class HourlyEmployee : Employee

{

// Get pay for the current pay period

public override decimal Pay()

{

// Time worked is in hours

return HoursWorked * PayRate;

}

}

// Derived subclass

public class SalariedEmployee : Employee

{

// Get pay for the current pay period

public override decimal Pay()

{

// Pay rate is annual salary instead of hourly rate

return HoursWorked * PayRate / 2087;

}

}

=Avoiding drawbacks=

This drawback can be avoided by using traits, mixins, (type) embedding, or protocol extensions.

Some languages provide specific means to mitigate this:

  • C# provides default interface methods since version 8.0 which allows to define body to interface member.{{cite web | url=https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#default-interface-methods | title=What's new in C# 8.0 | website=Microsoft Docs | publisher=Microsoft | access-date=2019-02-20}}{{cite book |last=Price | first=Mark J. |title=C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development: Build Applications with C#, .NET Core, Entity Framework Core, ASP.NET Core, and ML.NET Using Visual Studio Code | date=2022 | publisher= Packt |isbn= 978-1-098-12195-2}}{{rp|28-29}}{{cite book |last=Skeet|first=Jon|title= C# in Depth |date=23 March 2019 |publisher= Manning |isbn= 978-1617294532}}{{rp|38}}{{cite book |last=Albahari |first=Joseph |title= C# 10 in a Nutshell |date=2022 |publisher= O'Reilly |isbn= 978-1-098-12195-2}}{{rp|466-468}}
  • D provides an explicit "alias this" declaration within a type can forward into it every method and member of another contained type.{{cite web | url=https://dlang.org/spec/class.html#alias-this | title=Alias This | website=D Language Reference| access-date=2019-06-15}}
  • Dart provides mixins with default implementations that can be shared.
  • Go type embedding avoids the need for forwarding methods.{{cite web | url=https://golang.org/doc/effective_go.html#embedding | title=(Type) Embedding | website=The Go Programming Language Documentation | access-date=2019-05-10}}
  • Java provides default interface methods since version 8.{{cite book | title= "Effective Java: Programming Language Guide" |last=Bloch| first=Joshua| publisher=Addison-Wesley | edition=third | isbn=978-0134685991| year=2018}}{{rp|104}} Project Lombokhttps://projectlombok.org {{Bare URL inline|date=August 2024}} supports delegation using the {{code|@Delegate}} annotation on the field, instead of copying and maintaining the names and types of all the methods from the delegated field.{{cite web | url=https://projectlombok.org/features/experimental/Delegate | title=@Delegate | website=Project Lombok | access-date=2018-07-11}}
  • Julia macros can be used to generate forwarding methods. Several implementations exist such as Lazy.jl{{cite web | url=https://github.com/MikeInnes/Lazy.jl | title=MikeInnes/Lazy.jl | website=GitHub }} and TypedDelegation.jl.{{cite web | url=https://github.com/JeffreySarnoff/TypedDelegation.jl | title=JeffreySarnoff/TypedDelegation.jl | website=GitHub }}{{cite web |title=Method forwarding macro |url=https://discourse.julialang.org/t/method-forwarding-macro/23355 |website=JuliaLang |access-date=18 August 2022 |language=en |date=20 April 2019}}
  • Kotlin includes the delegation pattern in the language syntax.{{cite web | url=https://kotlinlang.org/docs/reference/delegated-properties.html | title=Delegated Properties | website=Kotlin Reference | publisher=JetBrains | access-date=2018-07-11}}
  • PHP supports traits, since PHP 5.4.{{cite web |title=PHP: Traits |url=https://www.php.net/manual/en/language.oop5.traits.php |website=www.php.net |access-date=23 February 2023}}
  • Raku provides a {{code|handles}} trait to facilitate method forwarding.{{cite web |title=Type system |url=https://docs.raku.org/language/typesystem#index-entry-handles_trait-handles |website=docs.raku.org |access-date=18 August 2022}}
  • Rust provides traits with default implementations.
  • Scala (since version 3) provides an "export" clause to define aliases for selected members of an object.{{cite web | url=https://docs.scala-lang.org/scala3/reference/other-new-features/export.html | title=Export Clauses | website=Scala Documentation | access-date=2021-10-06}}
  • Swift extensions can be used to define a default implementation of a protocol on the protocol itself, rather than within an individual type's implementation.{{cite web | url=https://docs.swift.org/swift-book/LanguageGuide/Protocols.html | title=Protocols | website=The Swift Programming Language | publisher=Apple Inc | access-date=2018-07-11}}

Empirical studies

A 2013 study of 93 open source Java programs (of varying size) found that:

{{blockquote|While there is not huge opportunity to replace inheritance with composition (...), the opportunity is significant (median of 2% of uses [of inheritance] are only internal reuse, and a further 22% are only external or internal reuse).

Our results suggest there is no need for concern regarding abuse of inheritance (at least in open-source Java software), but they do highlight the question regarding use of composition versus inheritance. If there are significant costs associated with using inheritance when composition could be used, then our results suggest there is some cause for concern.|Tempero et al., "What programmers do with inheritance in Java"{{cite conference |last1=Tempero |first1=Ewan |first2=Hong Yul |last2=Yang |first3=James |last3=Noble |title=ECOOP 2013 – Object-Oriented Programming |chapter=What programmers do with inheritance in Java |conference=ECOOP 2013–Object-Oriented Programming |year=2013 |pages=577–601 |chapter-url=https://www.cs.auckland.ac.nz/~ewan/qualitas/studies/inheritance/TemperoYangNobleECOOP2013-pre.pdf |doi=10.1007/978-3-642-39038-8_24 |isbn=978-3-642-39038-8 |series=Lecture Notes in Computer Science |volume=7920}}}}

See also

References