by herge · 10y ago · 0 comments
The naive implementation would be:
def process():
A()
B()
if [conditions for process 2]:
C'()
else:
C()
D()
You should implement it as: class Process1:
def A()...
def B()...
def C()...
def D()...
class Process2(Process1):
def C()...
[put C'() code here]
def process():
right_process = figure_out_right_process()
right_process.A()
right_process.B()
right_process.C()
right_process.D()
process() becomes a lot easier to test, since you only need to mock out/outsmart figure_out_right_process() instead of mimicking the right logic for [conditions for process 2]. You can test each process independently, since you don't need to fulfil the [conditions for process 2] in each test, and if those conditions should change, you only need to change figure_out_right_process() instead of at each branch in your code.It may look verbose with only one branch, but the second you have more than two processes, or nested branches, the class based way looks a lot cleaner.
2) For symmetry, I would make C abstract in the parent class, and create two subclasses, one implementing C, one implementing C'.
3) Having done that, the logic defining the order of the steps can be moved into the parent class.
4) If you want to mock things, it may help to make A, B, and D overridable in the parent class, too.