5 ms·
A polyglot's guide to multiple dispatch
- kevincox 11y agoIt's actually amazing how many people don't understand that many languages (particularly java) are single dispatch. None of my peers going through university even know what the term means and I have been docked marks because the prof computed the answer to a problem as if java supported multiple dispatch. I had to convince the professor to actually compile the code before she believed it. I wonder where this is best taught because it's a really interesting decision of languages yet very few people learn about it.
- klue07 11y agoI run into the same problem. I thought it was because I work in infosec so many people here don't have CS degrees or do a lot of dev work. I don't remember exactly where I learned dispatch, binding, etc. We did have a software dev class where I learned different design patterns. Visitor pattern always blows people's minds when they first see it in action hehe.
- DalekBaldwin 11y agoHow do they get so confused about it? Is it because Java also allows overloading, which is a sort of static multiple dispatch?
- twoodfin 11y agoExactly: foo.bar() has dynamic behavior based on the runtime type of foo. Why shouldn't foo.bar(baz) similarly be able to distinguish the runtime type of baz and pick the 'right' overload? Would it be more surprising to Java newbies if it did work that way?
- kazinator 11y agoBut then, what is the point of foo being associated with the class of bar? Multiple dispatch screams for the abolishment of methods as properties of objects, in favor of generic functions. Youc an still have the syntactic sugar obj.foo(arg), but it basically just translates to foo(obj, arg) where foo is a generic function not associated with foo's class in any way, and obj and arg have equal status. This generic function is what has methods.
- kazinator 11y agoBut then, what is the point of foo being associated with the class of bar? Multiple dispatch screams for the abolishment of methods as properties of objects, in favor of generic functions. Youc an still have the syntactic sugar obj.foo(arg), but it basically just translates to foo(obj, arg) where foo is a generic function not associated with foo's class in any way, and obj and arg have equal status. This generic function is what has methods. Say we implemented "funky" numbers, and would like to implement multiplication of funky and real. When funky is the left argument we get funky.mult(real). If real is no the left, we get real.mult(funky). These functions do the same thing (the multiplication is commutative), yet ... they have to live in separate classes? It is nonsensical. Under generic functions, we just have mult(real, funky) and mult(funky, real) which are methods of the generic mult(whatever, whatever). They both belong to the one generic function: that is the more reasonable organization.
- andrioni 11y agoThat's the way Julia does multiple dispatch, and it works well.
- StefanKarpinski 11y ago> But then, what is the point of foo being associated with the class of bar? One benefit is that the name `bar` is looked up in `foo`'s namespace, which means that it doesn't have to be in the current global namespace. This is a mixed blessing, but it's sometimes what you want.
- kazinator 11y agoThat's an interesting point and basically leads us to "member generic functions". An object has some static slot which is a function, and treated as a method: it can be called obj.meth(args, ...). But, this method is also a generic function. A generic function is a function; an object can have a function, and so an object can have a generic function.
- wtbob 11y agoYou're quite right, but does it make sense to conflate objects and namespaces that way? Might it not make more sense to separate the concerns?
- kevincox 11y agoThat's probably a large component of the problem. It's not unreasonable to expect both methods and overloading to use runtime types. I think this comment sums it up well: https://news.ycombinator.com/item?id=11528588 https://news.ycombinator.com/item?id=11528588
- twoodfin 11y agoI tripped over this as an undergraduate. On the surface, overloading looks like it has the same purpose and function as (virtual) method dispatch, but the difference between static and dynamic typing is subtle enough that they don't interact the way one might expect them to.
- eliben 11y agoThanks for the feedback! This is why I spent a section on showing the "failed attempt". It's surprising how many folks don't understand the difference between overloaded functions (compile-time dispatch) and true multiple dispatch (at run time).
- Splines 11y agoI have to admit, the failed attempt is the first thing I thought of. Thanks for including that and helping me understand why it doesn't work as expected.
- yareally 11y agoI learned about double/single dispatch when I was an undergrad taking a course on design patterns. Trying to wrap my head around the visitor pattern was kind of a pain, but once I saw how it was done in a language that supported double dispatch, it made a lot more sense. Overall, it was one of the more interesting and useful courses I took.
- deleted 11y ago[deleted]
- vvanders 11y agoOne downside of the brute-force approach not mentioned is there's a pretty heavy penalty paid for dynamic_cast. You're going to be bringing in RTTI which for a lot of C++ domains can be a non-starter.
- jcoffland 11y agoIt used to be common for RTTI to require jumping through extra hoops (i.e. adding compiler options) but it's supported by default by most C++ compilers these days.
- chubot 11y agoThe problem isn't build time "cost" though; it's runtime cost.
- santaclaus 11y agoAnd binary size, if that is something you have to worry about.
- eliben 11y agoTrue. Alexandrescu touches upon this in his Modern C++ take on multimethods. He uses static per class integers to uniquely identify them instead of RTTI. This is not unlike the special home-cooked "RTTI" LLVM uses (http://llvm.org/docs/HowToSetUpLLVMStyleRTTI.html http://llvm.org/docs/HowToSetUpLLVMStyleRTTI.html) to avoid the large cost of typeid and dynamic_cast, so that it can be built with -fno-rtti but still provide runtime identification for types. Naturally, these approaches require intrusion (special field/static member in each class)
- twoodfin 11y agoGeneralized multimethods are an inherently costly abstraction. This paper[1] provides a good survey of the state-of-the-art—at least as of 20 years ago—in the context of Dylan. I'll have to re-read that section of Modern C++ to recall the runtime algorithm, but I'd be interested on any pointers to newer research or engineering on dispatch techniques. It's too bad that (AFAIK) no 'mainstream' high performance language has a multiple dispatch abstraction that could motivate more work. [1] http://www.eecs.berkeley.edu/~jrb/Projects/pd.pdf http://www.eecs.berkeley.edu/~jrb/Projects/pd.pdf
- herge 11y agoMultiple 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 11y agoIsn't this single dispatch?
- jcoffland 11y agoThis looks like simple polymorphism to me. A.k.a., single dispatch.
- pasquinelli 11y 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 11y 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.
- jlg23 11y agoPeter Seibel's talk "Practical Common Lisp"[1] covers that from a different angle, also comparing multiple dispatch with the visitor pattern. [1] https://www.youtube.com/watch?v=VeAdryYZ7ak https://www.youtube.com/watch?v=VeAdryYZ7ak
- eliben 11y agoPart 3 in the series (coming some time next week hopefully) shows how multiple dispatch is done in CLOS (Common Lisp) :-) P.S. I love Seibel's PCL - great book
- deleted 11y ago[deleted]
- santaclaus 11y agoDoes anyone have a sense on the performance implications of each approach on contemporary compilers?