4 ms·
It’s dynamic dispatch because the decision about what code to call happens at runtime (via the switch statement) rather than compile time.
by josephg 7y ago
It’s dynamic dispatch because the decision about what code to call happens at runtime (via the switch statement) rather than compile time.
- uryga 7y agothis is particularly visible in the implementation of `plus` – `other` might not be a Point at all, so `other('x')` and `other('y')` might do anything; which i'd say is textbook (ad-hoc) polymorphism. i remember reading this somewhere: "branching on values is the ultimate dynamic dispatch" :)
- pbourke 7y agoBut that's essentially a table lookup, not a vtable lookup, right? Dynamic dispatch implies that you dispatch based on the class of the receiver. For instance, you can't have a Point3 value that uses Point's implementation of 'x' and its own implementation of 'toString' under this example.
- lalaithion 7y agolet Point3 = (x, y, z) => { let parent = Point(x, y); let self = (message, args=null) => { switch (message) { // getters case 'z': return z // some operations // (immutable, but that's not required) case 'toString': return `Point(x=${x}, y=${y}, z=${z})`; case 'move': let [dx, dy, dz] = args; // use our getters return Point(self('x')+dx, self('y')+dy, self('z')+dz); // let's get DRY! case 'plus': let [other] = args; return self('move', other('x'), other('y'), other('z')); default: parent(msg, args) } }; return self; };
- uryga 7y agomaybe "extremely late binding" would be more appropriate? it's true that usually "dynamic dispatch" means a vtable, but i think this is dynamic dispatch in spirit - in fact "dispatching" messages to implementations is pretty much the only thing a closure-object does :) i chose to write the impls inline, so they're p much impossible to reuse, but that's not required. > you can't have a Point3 value that uses Point's implementation of 'x' and its own implementation of 'toString' under this example. you can't do much of anything under this this example! i didn't think a whole object system would fit in a HN comment, i intended it to be minimal :)