Re:Pretending OOP Never Happened
by pbourke on Friday May 15, 2020 @06:45PM
(#23198400)
This is a neat example, but wouldn't dynamic dispatch imply polymorphism?
[ Parent
| on HN ]
It’s dynamic dispatch because the decision about what code to call happens at runtime (via the switch statement) rather than compile time.
But 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.
Re:Pretending OOP Never Happened
by lalaithion on Friday May 15, 2020 @10:42PM
(#23200021)
let 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;
};maybe "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 :)
this 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" :)