in reply to Re: replace conditionals with polymorphism
in thread replace conditionals with polymorphism

The only way you can get rid of the switch is to replace it with a object belonging to a dynamically chosen class. But how are you going to select the class? Of course with another switch statement (or other conditional logic)!
Or with a naming convention, right? But then you can do that with a dispatch table as well.

I think that the main thing that OOP polymorphism gains you is that it's a kind of plug-in architecture -- you can add handling for new cases by adding a new module, without changing the existing ones.

  • Comment on Re^2: replace conditionals with polymorphism

Replies are listed 'Best First'.
Re^3: replace conditionals with polymorphism
by tilly (Archbishop) on Feb 10, 2009 at 03:01 UTC
    A dynamically built dispatch table also offers the ability to add handling for new cases without changing the existing ones. And it has the benefits that it is simpler to do, and doesn't push you to spread your logic across multiple files.

    As ELISHEVA said, the big win with OO is that it gives you a framework to dispatch multiple related decisions.

      A dynamically built dispatch table also offers the ability to add handling for new cases without changing the existing ones. And it has the benefits that it is simpler to do, and doesn't push you to spread your logic across multiple files.

      Okay, cool... but I'm not quite seeing how you would set that up. So let's say you have a config file that lists all the allowed cases. Wouldn't you also need to add additional code to handle additional cases, and wouldn't that imply using "multiple files"?

        You are overcomplicating. See Re: replace conditionals with polymorphism for the format of a basic dispatch table. And then when I say "dynamically built" think about having a bunch of code that builds the hash that drives things. Just because it is dynamically built doesn't mean that you have to have offloaded stuff into a configuration file.

        For a realistically complex example of what you can do with a dynamically built dispatch table consider Why I like functional programming. Then think about what it would take to rewrite that example in an OO fashion.