I feel there is probably a well trodden design pattern to handle situations like the one below, but I’m just experienced enough to have come across it!
Basic Problem
The escense of the problem is say I have myClass with a method myMethod and I have a class extClass that extends myClass and I wish myMethod to have slightly different behaviour in extMethod then I can overwrite the method in the extended class, but then I end up having duplicated code.
Specific details
The specific problem that I’m trying to deal with is using MVC where I have a base model class which defines how inserts and deletes are performed. For some database tables I have implemeneted record versioning which is done with a class version_model which extends the base class and overwrites the insert/delete methods to add in triggers to create the record versions. This is all fine except that for some specific database table models I want to define custom insert/delete methods that will automatically handle inserts to nomalized tables (e.g. person table > addresses). This is ok except if I have to copy code from either the version_model or the base_model depending on which one it extends.
I was thinking this could maybe be solved with hooks, so my version_model and base_model insert/delete methods called ‘before_insert()’ and ‘after_insert()’ methods then I could add the additional functionality without duplicating the base functionality. Is there a better way to do this?
Separate out the code that differs from the code that’s common, keep the common code in the superclass and call the parent’s method from the subclass e.g. (php)
The hooks approach works too, in which case, you are doing more or less the same, but putting the logic into the superclass, which is an example of the template method pattern.
The usual alternative would be the strategy pattern, where you swap out the behaviours as objects, but this is more suited to situations where the number of combinations of methods you need would cause a very complex class hierarchy and may be overkill. Template or calls to parent methods are fine for this IMO. Try breaking down the process into the smallest steps you can. If there are several steps that vary across classes, use template/hooks. If only one does, use a function in the parent class for that.