I’m using visitor pattern to define a set of operations on some classes.
Some operations are commutative, so I end up with duplication in the visitor pattern code.
Let’s say I have classes A B C, and the operations: A*A, A*B, A*C, B*A, B*B, B*C, C*A, C*B, C*C.
A*A, B*B, C*C are unique.
A*B, B*A and friends will have code duplication
I could implement A*B, and make B*A call A*B but I will end up asking myself: in which file did I implement the operation between A and B again, in A or in B? (there will be about 6 classes, so I will ask this question a lot. 15 pairs of possible operations)
There is a risk of someone in the future making an infinite loop of A*B calling B*A calling A*B when implementing a new operation.
It’s unnatural to have a convention that decides which should be implemented A*B or B*A.
I could make a 3rd file with all the implemented functions which are called by either A*B and B*A, doesn’t seem very object oriented.
How would you solve this issue?
Thanks
(I could list some code, but it’s long and doesn’t illustrate the point easily)
I’m using visitor pattern to define a set of operations on some classes. Some
Share
You are right, you should definitely refrain from implementing
A*Bas a call ofB*A. In addition to a potential of creating an infinite chain of calls, that approach does not reflect the symmetry of the operation in your code, because the code is not symmetric.A better approach is to implement a “symmetric” operation in a helper class or as a top-level function, depending on what is supported in your language, and then make both
A*BandB*Acall that helper implementation.