Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: replace conditionals with polymorphism

by gnosti (Hermit)
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.

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]
[1nickt]: Is anyone using Method::Signatures ?
[choroba]: 10 bugs in the tracker?
[1nickt]: Yes, and recommendation against using it, in the doc for Devel::Declare, on whcih it is based.
[1nickt]: I asked the new $boiss what I should brush up on before starting work next week, and he named Moo, DBIx::Class and Method::Signatures
[1nickt]: choroba That's why I asked if anyone is using it :-)

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2017-11-24 13:17 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (349 votes). Check out past polls.