Is Double Dispatch an anti pattern?

by w0051977   Last Updated January 03, 2018 10:05 AM

Please see the link here: https://lostechies.com/derekgreer/2010/04/19/double-dispatch-is-a-code-smell/, which describes Double Dispatch as a code smell. Now see this link: https://lostechies.com/jimmybogard/2010/03/30/strengthening-your-domain-the-double-dispatch-pattern/, which talks about double dispatch strenghtening the domain. The same author of the second link (who believes in Double Despatch) wrote the code here: https://github.com/jbogard/presentations/blob/master/WickedDomainModels/After/Model/Member.cs and specifically this (which I believe is the Double Despatch pattern):

public Offer AssignOffer(OfferType offerType, IOfferValueCalculator valueCalculator) 
{ 
    DateTime dateExpiring = offerType.CalculateExpirationDate(); 
    int value = valueCalculator.CalculateValue(this, offerType); 
    var offer = new Offer(this, offerType, dateExpiring, value); 
    _assignedOffers.Add(offer); 
    NumberOfActiveOffers++; 
    return offer; 
} 

From what I can understand; the first author is saying that double despatch is an anti pattern because it violates SOLID principles. However, I believe the SOLID principles are violated in his code because of the way he has designed the classes; not specifically because of Double despatch. I also notice that the two articles were written within one month of each other in 2010.

Is Double Dispatch an anti pattern?



Answers 1


No, double dispatch is not an antipattern, it is a perfectly valid technique.

What the article describes is the expression problem. You want to be able to add new shapes and new drawing surfaces without violating the open/closed principle. Double dispatch is a possible solution to this problem. But it is possible to use it in such a way that it violates the open/closed principle, e.g. if you require each shape to have a draw method for each surface, then you would have to modify all shapes when adding a new drawing surface. If for some reason you want to avoid that, you could solve it by having some rendering adapters between the shapes and the surfaces, and use double dispatch to invoke the correct adapter.

In any case, even if some technique is in violation of the open/closed principle or SOLID in general, that does not make it an antipattern. SOLID is not an absolute good, it is just a set of guidelines (grouped under a catchy name) which are context-dependent and have limited applicability.

JacquesB
JacquesB
January 03, 2018 09:39 AM

Related Questions


Domain model design

Updated July 23, 2016 08:02 AM


What is a domain?

Updated October 23, 2017 18:05 PM