in reply to passing arguments
Also, what happens when you want to tell your print_multiple subroutine to print on a different file handle? Now your data structure is going to have to carry a file handle around with it, and everything that ever prints is going to have to worry about defaulting.
I submit that in the example you give, an object structure like the following may prove to be a little more loosely coupled and, in the long run, more maintainable.
Yes, there's a lot of code here. But most of it's setup code that's reusable. Each Class is responsible for a small reasonably well defined fragment of the overall task and I'd argue that as requirements grow, the whole thing is more maintainable. In the 'real world' I'd probably factor the 'FormatBold' thing into a subclass of some Format class. Once I've got the Format class factored out it becomes relatively easy to bring in a Formatter strategy class which knows that if we're formatting for HTML then bold looks like <b>...</b>, but if we're formatting for LaTeX, it looks like \textbf{...}, and so on.package Printable; sub print_on { my $self = shift; my($fh) = @_; print $fh $self->as_string; } sub as_string { $_[0]->value } sub new { my $proto = shift; my $scalar; my $self = bless \$scalar, ref($proto) || $proto; } sub set_value { my $self = shift; $$self = $_[0]; return $self; } sub value { ${$_[0]} } sub print { $_[0]->print_on(\*STDOUT) } package Decorator; use base 'Printable'; sub decorate { my $proto = shift; my($target) = @_; $self->new->set_target($target); } sub new { my $proto = shift; my $self = bless {}, ref($proto) || $proto; $self->init; return $self; } sub init { } package MultiString; use base 'Decorator'; sub count { my $self = shift; exists($self->{count}) ? $self->{count} : 1; } sub set_count { my $self = shift; $self->{count} = $_[0]; return $self; } sub as_string { my $self = shift; $self->target->as_string x $self->count; } package FormatBold; use base 'Decorator'; sub as_string { my $self = shift; '<b>' . $self->target->as_string . '</b>'; } package main; $thing = MultiString->decorate( FormatBold->decorate( Printable->new->set_value("Hello, world"); ) )->set_count(5); $thing->print;
Yes, there's slightly more initial setup involved. Yes, OO dispatch means things are going to be slower. But as a programmer I can go faster because, when it's done right, OO leaves you with small methods, that take a small number of arguments and which do exactly they say on the tin.
Done badly, well, Object Ravioli can be just as bad as (worse than?) procedural spaghetti. You just have to exercise Good Taste.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re2: passing arguments
by mstone (Deacon) on Apr 25, 2002 at 20:36 UTC |