Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Re: replace conditionals with polymorphism

by gnosti (Friar)
on Feb 09, 2009 at 17:44 UTC ( #742497=note: print w/ replies, xml ) Need Help??

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:


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.

Comment on Re: replace conditionals with polymorphism
Select or Download Code
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')

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://742497]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2015-12-01 06:21 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (795 votes), past polls