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

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
A short "private" constructor that allows you to call several subs in arbitrary order, without creating a new object.
package MyClass; use warnings; use strict; use diagnostics; # If the first parameter is already an object of this # class, simply return it, otherwise instanciate the # new class and return the object. # Upon error, returns undef. sub _new_or_old { my $invokant = shift; if( defined( $invokant ) ) { if( ref( $invokant ) eq 'MyClass' ) { return $invokant; } elsif( !ref( $invokant ) && ($invokant eq 'MyClass') ) { my $self = {}; bless( $self, $invokant ); return $self; } } # If not defined $invokant, we *could* use a default. # As of now, we treat it as any other error. return undef; }

The point of this snippet is to make it possible to have several constructors, which all can be called in an arbitrary order, or not at all (well, one must be, of course). Each constructor, instead of doing the usual constructor stuff, does this:

my $self = MyClass::_new_or_old( shift );
Which, when used the first time, my $obj = MyClass::init_stuff(), will return a new object, but subsequent calls like $obj->start_stuff() (see below) does not, it will return the same object, although MyClass::start_stuff() could very well have been used first, or without init_stuff.

So the rest of my class might look something like this:

sub init_stuff { my $self = MyClass::_new_or_old( shift ); # Set params here return $self; } sub start_stuff { my $self = MyClass::_new_or_old( shift ); $self->{'start_called'}++; # Do lots of really neat stuff here. return $self; } sub use_stuff { my $self = MyClass::_new_or_old( shift ); if( !$self->{'start_called'} ) { $self->start_stuff(); } return $self; } 1;
And lets say, that normally, I call start_stuff and then use_stuff. But sometimes, I want to call init_stuff before start_stuff, and I also want that if I call use_stuff first, I want that to both be valid, and implicitly call start_stuff. And an approach like this obviously won't work:
my $self = shift; if( !$self->{'constructor'}++ ) { $self = Myclass::new(); }
So. Why would anyone want to do something like this? Can't you just force the user to call a new() constructor before anything else, and be done with it? And force users to call things in order or throw errors? I have two main reasons:
  • I am converting something that already has this interface, and I want to keep it as close as possible, if I can. In reality, that is a pure functional interface, but I want to do it the same, but in perl and OO.
  • I got curious. Was it possible, and how? That is after all, how you become a good programmer, by investigating stuff that intrigues you. Well, one of the things. :) So now I understand refs, constructors and bless better. Something won!
In normal programming, this would most probably be called "very bad practice", especially since it will not make it very obvious what the script is doing (but that is what docs are for). Thus, I don't really recommend anyone using this "just because". But still, it works (far as I and my test cases can determine), and it scratches an itch I had, so I thought I'd share it with you. Maybe someone will find it useful.

Any comments on something I am doing in a bad way, or possible mistakes unaccounted for?


In reply to Multiple "constructors", possible to call several. by Dog and Pony

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2024-04-19 05:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found