In many langauges, super()
lets you call the parent method which you have overridden. I've been using super
in my Javascript (with fake object oriented implementation) to run common code for a long time without problems. Now I've finally hit a case where calling a protected
base class method would have been better than calling super
.
Here's a concrete example.
Grandparent -> Parent -> Kid
I needed to add a Kid. It's identical to Parent except for one method called someMethod. Kid's someMethod needed to do Grandparent's common stuff, but not Parent's specific stuff. So Kid's someMethod could not call super
because that would trigger Parent specific code. Instead of changing my grand class structure, I just made Kid duplicate Grandparent's common code.
Grandparent {
someMethod {
do common stuff
};
}
Parent: Grandparent {
someMethod {
super();
do parent specific stuff
}
}
Kid: Parent {
someMethod {
duplicate of common stuff
do kid specific stuff
}
}
In my book, duplicate code is bad. If only Grandparent wrote its common stuff as a protected method, I wouldn't need to duplicate code.
Grandparent {
protected commonMethod
virtual someMethod
}
Parent: Grandparent {
someMethod {
commonMethod
do parent specific stuff
}
}
Kid: Parent {
someMethod {
commonMethod
do kid specific stuff
}
}
Should I just completely stop using super
and switch to protected
methods for running common code? Are there any pitfalls to protected methods for running common stuff?