An idea I use when designing classes, is to “separate what changes from what does not change”.
An example is when using inheritance, and the derived class needs a small change in the method of a base class.
The naïve approach is to completely override the method from the base class.
However – that results in code duplication.
An alternative approach is:
- in the base class, split out the code that will change, into a separate function
- in the derived class, we only need to override this smaller function
- we have avoided duplicating the code (and so have less bugs)
- this function can be called a 'hook' since it provides a point to hook in and change behaviour
This approach is most similar to the Template Method design pattern.
An example is when using inheritance, and the derived class needs a small change in the method of a base class.
The naïve approach is to completely override the method from the base class.
However – that results in code duplication.
An alternative approach is:
- in the base class, split out the code that will change, into a separate function
- in the derived class, we only need to override this smaller function
- we have avoided duplicating the code (and so have less bugs)
- this function can be called a 'hook' since it provides a point to hook in and change behaviour
This approach is most similar to the Template Method design pattern.
Comments
Post a Comment