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.
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.