Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re^2: "Accessors (don't always) break encapsulation"

by mpeters (Chaplain)
on Jul 19, 2005 at 17:35 UTC ( [id://476194] : note . print w/replies, xml ) Need Help??

in reply to Re: "Accessors (don't always) break encapsulation"
in thread "Accessors break encapsulation"?

if ($obj->error) { $obj->log_error; }
I assume that you are referring to some of the logging modules out there that do this (eg, Log::Log4perl). In the simple case I agree with you (and it's actually what most of them do behind the scenes anyway). But the problem occurs when you have a computationally expensive error string. For instance:
use Data::Dumper; $obj->log_error(Dumper($some_very_large_structure));
By using the first approach, this expensive call could be avoided if the object just gave you an accessor so that you could make the decision yourself if the logging was necessary.

-- More people are killed every year by pigs than by sharks, which shows you how good we are at evaluating risk. -- Bruce Schneier

Replies are listed 'Best First'.
Re^3: "Accessors (don't always) break encapsulation"
by Ovid (Cardinal) on Jul 19, 2005 at 17:51 UTC

    Actually, I wasn't referring to those modules at all. Ignoring potential issue with premature optimization -- issues that I feel are more significant in Perl as it's rather slow and we don't have lazy evaluation -- if a logging module is there to allow the user to log stuff, then of course we need to figure out whether or not it's appropriate to call the method. In the example I used, it was a hypothetical example regarding something the programmer shouldn't have to worry about. In your example, you present an external API that the programmer should decide whether or not to call because that's the entire rationale behind the module.

    Sorry if I wasn't clear.


    New address of my CGI Course.

      We sure do have lazy evaluation!

      $obj->log_error( promise { Dumper($some_very_large_structure) } ); package Promises; use overload( '""' => sub { $_[0]->() } ); sub promise (&) { return bless $_[0], __PACKAGE__ }
Re^3: "Accessors (don't always) break encapsulation"
by tilly (Archbishop) on Jul 20, 2005 at 02:33 UTC
    I encountered almost exactly this situation. Here was my solution to keep code simple and avoid the excessive hit.
    $obj->log_on_error{sub {Dumper($some_very_large_structure)});
    The standard logging modules may not provide this functionality though.