Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

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:

$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.


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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2015-07-08 07:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (96 votes), past polls