One of the most powerful parts of the object oriented programming paradigm is polymorphism. Child classes may inherit then modify the behaviors of their parents. Through the inheritance tree of the classes we can move from the abstract to the specific. But it is also something I frequently see done… poorly… even in high level and popular applications (not going to name drop). You know it’s being done poorly when you see this
class foo {
public function save() {
/*
* A lot of steps
*/
$this->presave();
$this->dosave();
$this->postsave();
/*
* A lot more steps
*/
return;
}
protected function presave(){}
protected function postsave(){}
}
The idea is that the empty functions get defined later. This is the WRONG way to do this (I should know because I did it the wrong way for a long time).
For polymorphism to be effective, flexible and powerful, you must follow a doctrine of “for each method, one and only one task”. In other words, the above should look like this.
class foo {
public function save() {
$this->step1();
$this->step2();
$this->step3();
$this->step4();
$this->doSave();
$this->step5();
$this->step6();
$this->step7();
}
}
In live code each of the step functions will have a descriptive name of course - I’m just rattling off an example here. Now that each step of the save process is it’s own method we can modify the process at any step we choose by extending the function at the step we want to interrupt, do our interrupt action, then call the parent action.
So if you find yourself wanting to write an empty method in a concrete class that gets called as a ‘hook’ - its almost certain that the function calling that hook is doing too much and needs to be broken down into other functions. Note that this doesn’t apply to empty methods in abstract classes - they serve a different purpose altogether by requiring uncertain behavior to be defined before completion.