Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Using constant to override (abstract) methods.

by klekker (Pilgrim)
on Mar 28, 2011 at 08:29 UTC ( #895863=perlquestion: print w/replies, xml ) Need Help??

klekker has asked for the wisdom of the Perl Monks concerning the following question:

Dear fellow monks.

In a recent project I used an abstract base class as an interface and implemented its abstract methods using constants (for the sake of clarity; please see my code below).

Reading the docs for 'constants' I can't see anything wrong with this usage (constants become inline functions at compile time and I can override functions).

Now a colleague claims that I cannot rely on this behaviour because constants become *inline* functions and so the lookup might crash in some (unknown?) cases.

Well, the code works. But since it is supposed to run on a customers system and I don't want to have to fix it later if we run into trouble, I've decided to approach a higher instance:
so esteemed monks let me please ask you: is this approach okay or do you see any problems?
Or better: is this implementation considered harmful?

Thanks in advance!
k

Father.pm
package Father; use warnings; use strict; sub new { my $class = shift; my $self = {}; bless ($self, $class); return $self; } # INTERFACE sub aText { #implement die('Parent aText'); } sub aList { # implement die('Parent aList'); } 1;
Son.pm
package Son; use warnings; use strict; use Father; use base qw(Father); use constant { aText => 'This is a Text', aList => [qw(aaa bbb ccc)], }; sub print_son { my $self = shift; print 'Son:', $self->aText(), "\n"; print 'Son: ', join(', ', @{$self->aList()}), "\n"; } 1;
test.pl
#! /usr/bin/perl use strict; use warnings; use Son; my $s = Son->new(); print $s->aText(), "\n"; print join(', ', @{$s->aList()}), "\n"; $s->print_son();
Output:
This is a Text
aaa, bbb, ccc
Son:This is a Text
Son: aaa, bbb, ccc

Replies are listed 'Best First'.
Re: Using constant to override (abstract) methods.
by moritz (Cardinal) on Mar 28, 2011 at 08:40 UTC
    Now a colleague claims that I cannot rely on this behaviour because constants become *inline* functions and so the lookup might crash in some (unknown?) cases.

    Not true.

    The inliner does inline most "normal" calls to these subroutines, but since it can't catch every invocation (like soft references, method style invocations, goto &subname, maybe more...), it keeps the sub itself around.

    So it means you can use the use constant-generated subs as methods reliably.

    After all the inliner is just an optimization, and shouldn't change user-visible behavior.

      Thank you for this helpful explanation!

      k
Re: Using constant to override (abstract) methods.
by ELISHEVA (Prior) on Mar 28, 2011 at 09:39 UTC

    The more important issue to me is why?

    Although your approach 'works', I should think the use of constant to define overrides would be very confusing to future maintainers. For one, not everyone knows that constants are actually subs. Your coworker's confusion and many posts here I think testify to that. (look on Super Search).

    Second, use constant is not the obvious place to look for a method that overrides a superclass method.

    Third, it is somewhat misleading. The word "constant" implies immutable. That might lead someone to think that you have defined a final method. Perhaps that is even your reason for wanting to use "constant" this way? However, methods defined via use constant are not final. They can be overridden by any subclass because they are, after all subs. For example,

    use strict; use warnings; package Foo; use constant X => 100; sub new { bless([], $_[0]); } package Goo; our @ISA=qw(Foo); use constant X => 200; sub new { bless([], $_[0]); } package MeToo; our @ISA=qw(Foo); sub X { print "Hello World\n"; } my $oFoo = Foo->new(); my $oGoo = Goo->new(); my $oMeToo = MeToo->new(); print "$oFoo -> X = ", $oFoo->X, "\n"; print "$oGoo -> X = ", $oGoo->X, "\n"; $oMeToo->X(); #outputs Foo=ARRAY(0x8218ed0) -> X = 100 Goo=ARRAY(0x8218f10) -> X = 200 Hello World

    Performance wouldn't be a reason to use constants in this way either. Perl optimizes constant methods even when they are not explicitly defined as constants. According to Constant Functions:

    Functions with a prototype of () are potential candidates for inlining. If the result after optimization and constant folding is either a constant or a lexically-scoped scalar which has no other references, then it will be used in place of function calls made without & .

    There is nothing special about use constant. You can see the source code for the use constant pragma here. It is just Perl code that converts use constant X => Y into  sub X() { Y }. If anything, you are adding overhead to your startup code as compared with a simple sub definition since the pragma has to analyze each X => Y and generate the necessary symbols.

    Update: added comments about performance.

      So you are asking 'Why?!'? That's why I like reading PM! :)

      The example lacks some documentation that is included in the 'real' code, so I'm confident that my colleagues can deal with the code.

      But more important and interessting: 'why'?

      First of all: I don't claim that this is the best or most clever solution.

      The motivation for this was, that we have a bunch of small classes with immutable values (like for example: error-classes).
      You've got FileError, DatabaseError, FooError... all these errors share an errorCode, an errorText, an errorDescription and also a static list of errorFields which the error could affect.
      So I decided to create an interface Error for these errors so that every error-class (which are using constants so far) really implements all constants.

      k
      Dear ELISHEVA,

      I reconsidered your comment and talked about it with some colleagues.
      Now I have to confess that I changed the implementation and replaced constant by subroutines and let the code speak for itself.

      Thank you again for your feedback! :)

      k

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://895863]
Approved by moritz
Front-paged by moritz
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2020-10-22 13:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favourite web site is:












    Results (225 votes). Check out past polls.

    Notices?