Friday, September 16, 2022

When is inheritance useful?

A major disadvantage of inheritance is not being able to follow the program flow by ctrl + clicking function calls due to some functionality being implemented in ancestor classes. Therefore, I prefer composition over inheritance whenever possible. The one case where inheritance shines is reusing workflows. Let's say all your child classes have a run() method that calls f1(), f2() and f2() in order, where f1, f2, f3 functions are implemented in child classes. If we move the run() method to the ancestor class, child classes would just call that run method, saving you from duplicating the f1, f2, f3 calls in each child.

No comments:

Post a Comment