The Golden Rule of Accessor-Mutators

samtregar on 2002-11-07T21:44:52

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


Ooops.

Theory on 2002-11-07T21:56:16

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

Re:Ooops.

samtregar on 2002-11-07T22:04:41

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

Re:Ooops.

Theory on 2002-11-07T22:19:28

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

My golden rule of simple mutators:

pdcawley on 2002-11-08T07:40:53

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(...)
                      ->set_bar(...)
                      ->set_baz(...)
                      ->verify_object;
Clean, clear, extensible. I've been coding in this style for the best part of a year now, and it's just lovely. Thank you Smalltalk.

Re:My golden rule of simple mutators:

Ovid on 2002-11-12T00:16:32

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.

Re:My golden rule of simple mutators:

pdcawley on 2002-11-15T12:09:32

See the 'bloody good reason' caveat? I think 'accessor methods' come under the caveat. I was trying to emphasise my view that 'return $self' applied to a lot more than just 'set_foo'.