There is a parent class with a method which many children use but many children extend the method, what is the best way to extend it without violating DRY?
Here are my 2 current solutions:
1: The parent has a method which calls the reusable code which is relevant for all subclasses (do_this), then it calls a class specific method which all subclasses override. e.g.
class Parent(object):
def method(self):
self.do_this()
self.do_this_unique_to_class()
def do_this(self):
print 'every child wants to print this'
def do_this_unique_to_class(self):
pass
class Child(object):
def do_this_unique_class(self):
print 'Only class Child wants to print this'
2: Just use super and every child overrides the parents method. I don't like this solution as much. e.g.
class Parent(object):
def do_this(self):
print 'every child wants to print this'
class Child(object):
def do_this(self):
# call parents do_this
super(Child, self).do_this()
# then extend it
print 'Only class Child wants to print this'
Best Answer
The problem with your solution #1 is that you will never know if you later need some of
do_this_unique_class
done beforedo_this
.I would do something a bit different, but somewhat along the lines of #2, by splitting up the
do_this
method in the parent into methods that the parent makes available for the children and then have the children's 'do_this' method call the methods they need and add in their own logic.