Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

samtregar (2699)

samtregar
  (email not shown publicly)
http://sam.tregar.com/

Journal of samtregar (2699)

Thursday November 07, 2002
04:44 PM

The Golden Rule of Accessor-Mutators

[ #8828 ]
Never violate this rule:

Return unto others what you wish them to pass to you.

Or, in code, for every object $foo and every valid pair of get_bar() and set_bar(), this must work:

$foo->set_bar($foo->get_bar());

Violate this, particularly in an update to an existing system, and you will truely have hell to pay. This happened in a system I'm working on and by my count I'm fixing the fifth bug associated with it over a span of two months!

-sam

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • Assuming you're talking about code I wrote (and a bug I just fixed in Bricolage), I think I would design it differently today than I did a couple years ago when I wrote it, though I'm not sure how. I'll have to think about it...

    --David

    • Yes, the motivation for this revelation was your code, and the bugs that followed (and continue to follow; I'm working on one right now). However, I didn't write this just to tweak your nose. I feel like I'm onto something here... A fundamental rule of OO design, perhaps, or at least a very useful lesson.

      -sam

      • I didn't think you were tweaking my nose, and I agree that what you're "onto" is indeed an excellent guiding principal. Here's another that I'll follow in other future projects: Never, ever use 0 (that's a zero) as an object identifier.

        --David

  • Simple mutators set_foo shall return the object mutated, they shall not return the new value, you already knew that. They shall not return the old value, if you wanted to know that you should have asked. If a simple mutator fails, it shall throw an exception.

    Actually, in general, and unless there's a bloody good reason for returning something else, methods should always return $self or throw an exception.

    Why?

    my $thing = Class->new->set_foo(...)
                 

    • pdcawley wrote (emphasis mine):

      Actually, in general, and unless there's a bloody good reason for returning something else, methods should always return $self or throw an exception.

      Did you mean mutators should always return $self? Having an accessor return $self would be disappointing.