Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re^4: object oriented module question

by rhesa (Vicar)
on Sep 07, 2007 at 18:17 UTC ( [id://637730]=note: print w/replies, xml ) Need Help??


in reply to Re^3: object oriented module question
in thread object oriented module question

exussum0 didn't object to delegation in general, just to the way I did it in my example. And he has a good point too: It's usually better to access the delegated object through an accessor method, because of the arguments he gave, and because it allows lazy loading. In that way, the delegated object is only constructed on first use. It also allows easier overriding.

If I were to rewrite my example using an accessor, it'd look something like this:

package My::Module; sub new { my $class = shift; my $self = {}; # no clutter! bless $self, $class; } sub some_method { my $self = shift; # we use it here my $result = $self->_csv->some_csv_action( @input ); # uses access +or } sub _csv { my $self = shift; # allow to be set from outside if(@_) { $self->{_csv} = shift; } # default to Text::CSV if( !defined $self->{_csv} ) { require Text::CSV; $self->{_csv} = Text::CSV->new( 'some args' ); } return $self->{_csv}; }
I'm sure that could be refined further, but it demonstrates the basic idea. The benefit should be clear: it's now possible to supply a My::Module object with a different CSV object, which makes testing easier, as well as customizing the behavior of our class.

Replies are listed 'Best First'.
Re^5: object oriented module question
by former33t (Scribe) on Sep 10, 2007 at 16:25 UTC
    That is definitely an improvement over the way I've been doing things. Thanks for the code example. Luckily (for them), I'm the only one who has to maintain my code, but that is much cleaner and much more modular.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (6)
As of 2024-04-23 13:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found