in reply to Re: Fun with Farcical Factories (Was: Re^4: Your favorite objects NOT of the hashref phylum)
in thread Your favorite objects NOT of the hashref phylum
In your example $self->{logger}->( @_ ) I will assume you meant something like $self->{logger}->log( @_ )
Now you could correctly point out that the same could be achieved with a file scoped hash and a package sub (rather than using OO). But if you had just used a global filehandle with a print statement at every log point (as I often see in code) you would not be able to extend it.package Logger; my $singleton_object; sub new { my $class = ref $_[0] || $_[0]; $singleton_object ||= bless $singleton_object, $class; } sub logfile_handle_for_method { my $self = shift; my ($package, $subroutine) = @_; # not cross-platform... $package =~ s!::!/!g; my $filename = "/var/log/$package/$subroutine.log"; return $self->{filehandles}{$filename} if $self->{filehandles}{$fi +lename}; my $fh; open $fh, ">$filename" | die; $self->{filehandles}{$filename} = $fh; } sub log { my $self = shift; my ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask) += caller(1); my $fh = $self->logfile_handle_for_method($package, $subroutine); print $fh, @_; }
And that's really one reason why drilling rules like "use Singletons not globals" into younger or less skilled developers - it may not often buy them much, but it might prevent them from doing something stupid. You would hope that you could teach them about how to decide when to apply abstraction (which is all this really is about) but experience tells me that an abstract concept like abstraction is not universally understood by people wanting to be programmers.
|
|---|