Refactoring: Replacing inheritance with delegation

All too often inheritance is used in the wrong scenarios. Inheritance should really be used when it makes logical sense, however we often see it used for convenience. Take this example:

class sanitation {
  public function washHands(){ 
    return "cleaned";
  }
}

class child extends sanitation { }

$child = new child();
$child->washHands();

In this instance child is not a "sanitation" So inheritance doesn't actually make sense here. We can refactor this to delegate handwashing by passing an instance of sanitation into the child constructor and calling it that way.   Now let's look at this example refactored child class:

class child {
  public function __construct($sanitation){
    $this->sanitation = $sanitation;
  }
  public function washHands(){
    $this->sanitation->washHands();
  }
}
$child = new child(new sanitation);
$child->washHands();

Comments

Popular posts from this blog

The Concept of True North in Lean Methodology: A Toyota Perspective

The Archetypes of Staff Engineers: How to Excel and When Your Business Needs One

Serverless Architectures: Simplifying Backend Development for Scalable Apps in 2025