3

A few times in my career I've encountered design problems that couldn't be elegantly solved with single dispatch and required double dispatch (which I implemented using visitors). However, I've never encountered a problem that required triple dispatch.

They must be exceedingly rare, but that doesn't mean they don't exist. Has anyone actually had a real-life (not textbook/academic) design problem that could optimally be solved with triple dispatch?

Alexey
  • 237
  • 1
  • 4

1 Answers1

4

Consider a repository of citation information. containing books, articles, journals, edited books, and conference papers. Your task is to format the contents of the repository for consumption.

Let's take two approaches to formatting. National Library of Medicine (derived from the Vancouver Project) specifies citations in a particular way, mostly affecting how author names are laid out. NLM differs from American Psychological Association (APA) formatting. Your task is to provide a general approach to formatting citations using at least these two formatting standards. The visitor pattern is a good fit.

Now, you have to publish these citations and your choice of outputs are: plain text, PDF, HTML, RTF and MS Word (OOXML) or ODF. Some of these items require different layout strategies, depending on the type of the format (APA indents following lines, NLM doesn't).

"Double visitor" doesn't work so well. You really need something equivalent to "triple dispatch".

Now, that is not to say that there aren't approaches that get around the triple dispatch. For the above example, I ended up creating mixins and helper classes to provide the final publication version. These mixins and helpers are really where the 3rd dispatch occurred. I also evaluated publishing in a common denominator output and post-processing it to get the right output format, but that was ... bulky.

BobDalgleish
  • 4,644
  • 5
  • 18
  • 23
  • Out of curiosity, in what language did you implement it? – coredump Aug 01 '15 at 19:41
  • That's quite interesting. Am I correct that the three arguments dispatched upon were the type of the source, the formatting standard and the output format? With 5 types of sources, 2 formatting standards and 6 output formats, how many methods would you have implemented with triple dispatch? Sixty? – Alexey Aug 01 '15 at 20:41
  • The implementation was in Java. Since Java uses compile-time dispatch, I defined an interface for the formatters, and a method in the citation to invoke the formatter. Each formatter used dependency inversion to perform the layout operations as it was being formatted. – BobDalgleish Aug 01 '15 at 23:10