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

Faking new() method in high-level package

by belden (Friar)
on May 08, 2002 at 21:26 UTC ( [id://165191]=perlquestion: print w/replies, xml ) Need Help??

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

I've finally wrapped my mind around objects. Sort of. My first real OO project is to develop a set of utilities for working on some of my company's proprietary tables. One of the things that my nascent module has is two packages - one is a bunch of low-level methods for interacting directly with the table data, and the other is a higher-level set of methods for doing more interesting things using (you guessed it) the low-level methods; sorting, deduping, that kind of stuff.

One of the things that I've been bitten by in my test programs is that my low-level package has the object constructor, not the high-level package. The 'bite' is that sometimes I forget, and instead of typing

my $tool = LowUtils->new ( file => 'foo' )

I type

my $tool = Utils->new ( file => 'foo' )

Today I realized that in the high-level package I can just add a new method which calls the low-level package's new method. Here's some sample code to show what I ended up doing:

#!/usr/bin/perl BEGIN { use strict; use warnings; } package Utils; sub new { # discard my class... shift(@_); # ...and invoke LowUtils::new as though # it were called by our caller. LowUtils::new ( 'LowUtils', @_ ); } sub get_numlines { my $self = shift; return scalar @{$self->{FILEDATA}}; } sub DESTROY { print "\tthis is the Utils destructor\n"; } 1; # end package Utils package LowUtils; @LowUtils::ISA = qw ( Utils ) ; sub new { my $proto= shift(@_); my %args= @_; my $class = ref($proto) || $proto; my $self = {}; $self->{FILENAME} = $args{file}; $self->{FILEDATA} = []; bless $self, $class; $self->init; return $self; } sub init { my $self= shift(@_); my %args= @_; open DAT, $self->{FILENAME} or return undef; @{$self->{FILEDATA}} = <DAT>; close DAT; return $self; } sub DESTROY { print "\tthis is the LowUtils destructor\n"; } 1; # end package LowUtils my $utils = Utils->new ( file => $0 ); print 'Utils: lines = ', $utils->get_numlines, "\n"; undef $utils; my $low = LowUtils->new ( file => $0 ); print 'LowUtils: lines = ', $low->get_numlines, "\n"; undef $low; exit;
Output:
Utils:    lines = 72
        this is the LowUtils destructor
LowUtils: lines = 72
        this is the LowUtils destructor

I arrived at this solution after deciding that it probably wouldn't be smart to set @Utils::ISA to refer back to LowUtils. My questions:

  • This works now - can I expect it to work through future versions of Perl?
  • Is this an okay way to do it, or is there a better way? Or should I not be doing this at all?
  • Along the lines of 'should I not be doing this' - what mishmash am I potentially introducing into my module? I tossed in two DESTROY methods to make sure that Utils::DESTROY doesn't get called on objects invoked with Utils->new() - can anyone think of anything that I'm missing?
Thanks -

blyman
setenv EXINIT 'set noai ts=2'

Replies are listed 'Best First'.
Re: Faking new() method in high-level package
by jreades (Friar) on May 08, 2002 at 21:54 UTC

    It looks like you've come with a workable solution, but not a particularly flexible one. What happens if you extend Utils with Utils::MidLevel?

    As you clearly understand, no software is smart enough to know that if you typed new Utils() you really meant new Utils::LowLevel(), but from a software design standpoint there's no reason you couldn't have a single new() function that handled instantiation for Utils, Utils::MidLevel, and Utils::LowLevel.

    The way to do that, if I remember correctly, is to recall that you can bless an object into almost any class you want. So, where you normally see bless $self, $class, there's no reason not to interpolate $class to be any of the three classes you've designed.

    Here's where you can get tricky... what if each of these classes had an init() function that would perform class-specific stuff. Your code could become something like this:

    package Utils; sub new { my $class = shift; my $self = {}; # Bless into the appropriate class my $obj = bless $self, $class; $obj->init(@_); return $obj; } sub init { # does nothing } package Utils::MidLevel @Utils::MidLevel::ISA = qw(Utils); sub init { my $self = shift; my @args = @_; $self->SUPER::init(@args); # Now do initialization of object } package Utils::LowLevel @Utils::LowLevel::ISA = qw(Utils::MidLevel); sub init { my $self = shift; my @args = @_; $self->SUPER::init(@args); # Now do initialization of this class }

    Your initialization could then be:

    my $object = new Utils::LowLevel();

    But this would also work:

    my $object = new Utils();

    I guess this is kind of tangential to your question, because what you're doing is the only way of doing what you appear to want to do (save yourself from test failures that are the result of typos). However, I'd strongly suggest that this is not a good coding practice for the reason I outlined above (to put it another way, if a Util is always a LowLevel Util then I'm a little unclear on why you'd have a separate class at all).

    HTH

    PS. As with all things Perl there are other ways to do this, but the init() system is fairly simple to comprehend and gives you a fair amount of flexibility.

      Okay, this clears a bit of the mist in my head. Blessing into whatever class I want is certainly, err, what I want. Your example of having an init() method is something I'll have to incorporate into my code; you're right on it being easily understandable. I also notice that you went with Utils and Utils::LowLevel rather than my Utils and LowLevelUtils - obviously I'm still learning the basics of designing a useful package hierarchy.

      Now I have a question of laziness. Having re-arranged your code a bit:

      #!/usr/bin/perl { package Utils; sub new { my $class = shift; my $self = {}; # Bless into the appropriate class my $obj = bless $self, $class; $obj->init(@_); return $obj; } sub init { # does nothing } 1; } { package Utils::MidLevel; @Utils::MidLevel::ISA = qw(Utils); sub init { my $self = shift; my @args = @_; $self->SUPER::init(@args); # Now do initialization of object } 1; } { package Utils::LowLevel; @Utils::LowLevel::ISA = qw(Utils::MidLevel); sub init { my $self = shift; my @args = @_; $self->SUPER::init(@args); # Now do initialization of this class } sub foo { print "foo\n" } 1; } print "Creating new Utils object\n"; my $util = new Utils; #$util->foo(); # can't find method :( print "\n"; print "Creating new Utils::MidLevel object\n"; my $mid = new Utils::MidLevel; #$mid->foo(); # can't find method :( print "\n"; print "Creating new Utils::LowLevel object\n"; my $low = new Utils::LowLevel; $low->foo(); print "\n"; exit;
      If I add
      sub foo { Utils::LowLevel::foo }
      into Utils and Utils::MidLevel, then the $util and $mid objects can both find the foo method.

      Now, if I'm pig-headed and am dead set against adding those kinds of stubs into Utils and Utils::MidLevel and similarly want to have Utils and Utils::MidLevel be able to access lower-level methods in this manner:

      sub do_highlevel_stuff { my $self = shift; my $value = $self->get_lowlevel_value; # ... }
      rather than

      sub do_highlevel_stuff { my $self = shift; my $value = Utils::LowLevel::get_lowlevel_value($self); # ... }

      Well - can I have my cake and eat it too? That is, can I keep Utils aware of methods in Utils::MidLevel aware of methods in Utils::LowLevel without having to go through double-colon acrobatics (plus calling methods as regular functions)?

      I'm guessing the answer to the above question is no; without stubs and without calling the methods functionally, there is no way to do what I want - just thought I'd ask on the off chance that there's a crafty way to do this. :)

      Sorry if this post is hard to read due to incorrect usage of OO terminology (or other CompSci terminology for that matter)

      (Good catch on extending Utils with Utils::MidLevel, btw. I have been thinking, "Gee, this really isn't really a low-level table action, nor a high-level action... it's more mid-level...")

      blyman
      setenv EXINIT 'set noai ts=2'

        The problem that you're running into is that you're trying to run inheritance the wrong way (and possibly for the wrong reasons).

        The short answer is that you can't have a high-level class be aware of a low-level class' functions without embedding those kind of ugly stubs in your code (at least, not that I know of).

        The longer answer is this:

        If all subclasses of class Utils will have a method called do_something(), then having a method stub (meaning a method that does nothing) is appropriate.

        sub do_something() { return 1; }

        This would allow you to pass around objects belonging to any of Util's subclasses without worrying about their specific type. You would know that all Util subclasses could be made to perform some action simply by calling do_something(), whether or not the something to be done is the same for each subclass.

        Looked at another way, if Util needs to be aware of a subclass' implementation of method then you've got the either the class hierarchy, or the class in which this method is declared, wrong. If calling Util::method() relies on Util::LowLevel::method(), then method() doesn't belong in the Util class since it doesn't work at that level of abstraction.

        Does that make sense?

        The other thing that is sounds like you are running into is the conflict between inheritance and composition.

        You're trying to build a toolset to be offered by Util while relying on a LowLevel toolset supplied by a class that inherits from it. This sounds like a case for composition, not inheritance -- HASA vs. ISA. If your Util class needs a LowLevel toolset, then you might want to tackle it this way:

        package Utils; sub new { my $class = shift; my @args = @_; my $self = {}; $self->{toolset} = new Toolset; return bless $self, $class } sub read() { my $self = shift; $self->{low_level_stuff} = new Functions::LowLevel; } sub doSomeOperation() { return $self-{low_level_stuff}->read(); } package Toolset sub new {} sub read {} package Toolset::LowLevel @Toolset::LowLevel::ISA = qw( Toolset ); sub new {} sub read { my $self = shift; return $self->readLine(); }

        This approach probably only makes sense if you plan on having more than one toolset subclass (or you're doing a lot of OO work for little return). But now you have isolated Utils from the LowLevel Toolset class successfully and you could, for instance, make Toolset smart enough to instantiate itself differently (and return different low-level toolsets) based on the platform or something. This is one way to get a balance of abstraction and functionality, although there are, undoubtedly, many more

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://165191]
Approved by IlyaM
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2024-04-25 22:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found