Recently, I had an interesting concept pop into my mind.
Is it possible to use constants as package methods, and if so,
is there any compelling reason why people don't do that more often?
A little research showed me that yes, it is possible to use constants
as package methods, so now I open the question up to my fellow monks:
Is it a BAD THING(tm) to use constants as package methods?
Pros:
- It's a constant. It can't be changed.
- But it can still be overridden by derived classes.
- Another 'use constant' line
- A subroutine that computes a value. Not necessarily a constant.
- Can use either indirect or OO invocation syntax.
- The meaning is explicit in the 'use constant' line.
Cons:
- Lose inlining due to method lookup
- No interpolation in strings, without the standard constant trick.( ie. @{$obj->VALUE} )
- Derived classes MUST consistently call as a method invocation, not as a subroutine
Example:
test.pl
#!perl
use strict;
use warnings;
use My::Package;
use My::Package::Derived;
local $\ = "\n";
my $item1 = new My::Package;
my $item2 = new My::Package::Derived;
print $item1->SOME_VALUE;
print $item1->SOME_DERIVED_VALUE;
print $item1->ANOTHER_DERIVED_VALUE;
print '-' x 30;
print $item2->SOME_VALUE;
print $item2->SOME_DERIVED_VALUE;
print $item2->ANOTHER_DERIVED_VALUE;
My/Package.pm
package My::Package;
use strict;
use warnings;
use constant SOME_VALUE => 12;
use constant SOME_DERIVED_VALUE => 14;
use constant ANOTHER_DERIVED_VALUE => 21;
sub new {
bless {}, ref($_[0]) || $_[0];
}
1;
Derived.pm
package My::Package::Derived;
use strict;
use warnings;
use My::Package;
our (@ISA) = qw[My::Package];
use constant SOME_DERIVED_VALUE => 15;
sub ANOTHER_DERIVED_VALUE() {
int(rand(100)+1);
}
1;
References
2002-03-13 Edit by Corion : Fixed title (almost) per request
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.