http://www.perlmonks.org?node_id=411900


in reply to Re^6: Depends...
in thread Review: CGI::Prototype

What's wrong with an if statement?

The main problem with an if statement versus polymorphism is where the logic resides. The former leaves the logic in the routine with the if, so we have something like this:

*isa=*UNIVERSAL::isa; sub with_the_if { ... if (isa($foo,'Type1')) { return $foo->method1 } elsif (isa($foo,'Type2')) { return $foo->method2 } else { return $foo->method3 } }

This is problematic because it makes thing hard to extend later on. The OO way to do it puts the logic on the OUTSIDE of the routine with the if. So now we do:

sub Type1::generic_method { $_[0]->method1 } sub Type2::generic_method { $_[0]->method2 } sub TypeX::generic_method { $_[0]->method3 } @Type1::ISA=@Type2::ISA=qw(TypeX); sub with_the_if { ... return $foo->generic_method }

Now code in with_the_if() doesnt have to change when a new type gets added to the framework. It-just-works because whichever type $foo is there will be a generic_method defined that knows what to do. (Or there should be if its work properly). Now to change the behaviour of the system the outside user never has to touch with_the_if(), he just needs to define Type9::generic_method().

BTW, this isnt meant to add anything to the C::P vs C::A debate, I know neither well enough to say anything, but just an answer to the one question.

---
demerphq

Replies are listed 'Best First'.
Re^8: Depends...
by hardburn (Abbot) on Dec 02, 2004 at 19:23 UTC

    Thanks for going into more detail. I'm not versed enough in C::P to know if it is good enough for this, either, but I'm sure C::A was not designed for a polymorphic view of the world. And I'm also sure that polymorphism is the way to go for this task.

    "There is no shame in being self-taught, only in not trying to learn in the first place." -- Atrus, Myst: The Book of D'ni.