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

Navigating the Jungle of Web Traffic: A Technical Team Lead's Guide to "I'm a Celebrity, Get Me Out of Here"

TCP Handshake over IPv6

The Vital Importance of Secure Wi-Fi Networks