Contact Me

Replace Inheritance With Delegation

Create a field with a superclass object in it, delegate methods to the superclass object, and get rid of inheritance.

 It is used when You have a subclass that uses only a portion of the methods of its superclass. The solution is to replace an inheritance hierarchy with an object that contains another object, in order to improve the readability and maintainability of the codebase. This can be useful when a class hierarchy is complex and difficult to understand or maintain.

 For example, consider the following class hierarchy, which inherits properties and methods from several classes:

class Shape {

draw() {

  console.log('Drawing shape');

}

}

class Circle extends Shape {

draw() {

  console.log('Drawing circle');

}

}

class Rectangle extends Shape {

draw() {

  console.log('Drawing rectangle');

}

}

 To make the hierarchy more readable and maintainable, we can replace the inheritance with delegation by creating a new class that contains a shape property and delegate the methods to the contained object:

class Circle {

constructor() {

  this.shape = {

   draw: () => console.log('Drawing circle')

  }

}

}

class Rectangle {

constructor() {

  this.shape = {

   draw: () => console.log('Drawing rectangle')

  }

}

}

const circle = new Circle();

circle.shape.draw(); //Drawing circle

const rectangle = new Rectangle();

rectangle.shape.draw(); //Drawing rectangle

 In this example, we have replaced the inheritance with delegation by creating a new class that contains a shape property and delegate the methods to the contained object. This improves the readability of the class hierarchy by reducing the number of classes and making it clear that each class is containing a shape object and delegate the methods to it.

 Another benefit is that it allows for more flexibility in the codebase. For example, in the above example, if we need to change the implementation of the draw method for a certain shape, we can simply change the implementation of the shape object within that class without affecting other classes.