Suppose I have a parent class P with a method main
that implements the core functionality of the class. main
itself calls a function defined in another module called parent_function
, with signature parent_function(x, y)
.
e.g.
from my_module import parent_function
class P:
def main():
# do something
x = P.calc_x()
y = P.calc_y()
z = P.calc_z()
# execute `parent_function`
parent_function(x,y)
# do more things
Now suppose I have a child class C which differs from P by calling child_function
, with signature child_function(x,y,z)
, instead of parent_function(x,y)
. To call child_function
with its different signature, I have to rewrite the whole of the main method, changing just one line
e.g.
from my_module import child_function
class C(P):
def main():
# do something
x = P.calc_x()
y = P.calc_y()
z = P.calc_z()
# execute `child_function`
child_function(x,y,z)
# do more things
This is a violation of the DRY principle.
How can I redesign the code to avoid rewriting the whole main
method?
Some ideas:
-
Turn
parent_function
,child_function
into methods of P / C, setz
as an instance variable so the signatures of the two methods can be the same. I dislike this solution as in my case it does not make sense forz
to be an instance variable. -
Store the output
(x,y,z)
into a dictionary, change the signature ofparent/child_function
to accept**kwargs
, and ignore unused kwargs inparent_function
.
Aucun commentaire:
Enregistrer un commentaire