[Prev][Next][Index][Thread]
Re: simple method dispatch question
"Jeff Dubrule" <igor@pobox.com> wrote in message
20001111005047.P26044@secret-lab.dartmouth.edu">news:20001111005047.P26044@secret-lab.dartmouth.edu...
>> This looks interesting, but it seems to me to obfuscate
>> semi-trivial (and very conventional) conditional logic using
>> the dispatch mechanism. Doesn't this tend to make write-only
>> code outside of trivial examples?
> Not at all. Here's a not-quite-as-trivial example: consider
> writing a virtual machine...
OK, please keep in mind that I've already withdrawn my first-glance
objection to Bruce's example and then allow me to play devil's advocate.
> define function run(program)
> for (opcode in program)
> run-instruction(opcode);
> end for;
> end function;
> define method run-instruction(instruction == #add)
> push(*stack*, pop(*stack*) + pop(*stack*));
> end method;
> define method run-instruction(instruction == #multiply)
> push(*stack*, pop(*stack*) * pop(*stack*));
> end method;
> ..
> ..
> ..
> This is certainly tons cleaner than a traditional switch statement,
> just about as fast, you can split opcode implementations up into
> multiple files, and you can even add opcode extensions later just by
> defining new methods.
Cleaner I'm not so sure I agree with. At a glance it seems to require more
lines of code -- much of which is boilerplate code -- than a ladder of if
statements would. On the other hand each instruction is set out in a
fashion which is much more clearly separate, so this may cancel out.
Speed-wise I'm sure it's almost as fast in any half-decent compiler. But
the last two points are what make me shiver.
Consider a VM written the way you've just advocated -- opcode
implementations scattered across files and opcode extensions added later,
probably in a different module entirely. Now consider someone new being
brought into the project. Throw the source code at the newbie and watch him
founder.
I withdraw my objection to the trick, as I said. I can see its advantages
now that I've tried it out for a bit. But it is the kind of trick which
*CAN* create write-only code and use of it would have to be policed against
this.
References: