3 ms·
Multiple dispatch is a great way to handle branching complexity. Let's say you have Process 1 which requires Steps A, B, C and D, and Process 2, very close to P
by herge 10y ago
Multiple dispatch is a great way to handle branching complexity. Let's say you have Process 1 which requires Steps A, B, C and D, and Process 2, very close to Process 1, which requires Steps A, B, C' and D.
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.
- shaunparker 10y agoIsn't this single dispatch?
- jcoffland 10y agoThis looks like simple polymorphism to me. A.k.a., single dispatch.
- pasquinelli 10y agoi don't understand what this has to do with multiple dispatch. only the this argument is dynamically dispatched on. multiple dispatch is the same idea, except with more than just the this argument being dispatched on, allowing you to define custom methods for any combination of possible arguments and getting to the right one at runtime.
- Someone 10y ago1) I do not see how that's multiple dispatch. In C++ parlance, it requires C to be virtual, but that's it. 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.
- hboon 10y agoThis is single dispatch.
- deleted 10y ago[deleted]