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


in reply to replace conditionals with polymorphism

Here is a simple example. I had been using conditionals in a project to be able to run the same code in console mode, or with a GUI output. I replaced these conditionals with lines like this:

$ui->refresh

In the Text package, refresh is just a stub, i.e. refresh {}, while the Graphical package has a functioning refresh routine. (In general, the stubs might better be in the base class.) I create the object in the first lines of the program based on a command-line switch.

The program is a single file. I share data by using our ($var1, @var2, %var3) enabling all packages to access these variables without a package prefix.

This is how I got the polymorphism to work, thanks to the advice of some helpful monks.

use strict; use warnings; package UI; our @ISA = (); sub new { my $class = shift; return bless {@_}, $class } sub hello {print "superclass hello\n"}; package UI::Graphical; our @ISA = 'UI'; sub hello {print "make a window\n";} package UI::Text; our @ISA = 'UI'; sub hello {print "hello world!\n";} my $ui = UI->new; $ui->hello; my $tui = UI::Text->new; $tui->hello; my $gui = UI::Graphical->new; $gui->hello;

UPDATE: Changed @ISA = '' to </c> @ISA = ()</c> as cautioned by chromatic.

Replies are listed 'Best First'.
Re^2: replace conditionals with polymorphism
by chromatic (Archbishop) on Feb 09, 2009 at 20:01 UTC
    package UI; our @ISA = '';

    Careful; you've just inherited from a class with no name.

      You likely know this, but others mightn't:

      Perl provides the class with no name. It's identical to the main:: namespace:

      package Hello; @Hello::ISA=''; package main; sub p { print for @_ }; Hello->p('World')