Posts

Showing posts from January, 2015

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();