First journal entry and accessors

TheNomad on 2006-06-19T17:34:45

I finally registered on this site after looking for some ideas about how to automagically generate accessors. I had spent a whole day trying to get Class::MakeMethods do what it is supposed to do, especially in relation to arrays.

See perl doesn't have a standard way of dealing with accessors and I've never liked the common $foo->bar, $foo->bar('some value') type of accessors. I like "Afforability Accessors", so $foo->get_bar and $foo->set_bar('some value'). I was encouraged by Damian Conway's view that best practice is to use get_ and set_. Yippee!

So I gave up on Class::MakeMethods and decided to play with Class::Accessor. Wow! What a module! It is simple and it does what it says on the package. It is even easy to change the way that 'get' and 'set' work.

Which brings me to another point. In perl people write setters that return the value being set. Surely, it would be better to return the object, because that way it is easy to chain accessors.


chaining

TeeJay on 2006-06-19T20:48:35

..but if you chain operators you aren't checking for failure :)

Re:chaining

runrig on 2006-06-19T21:10:31

That is not necessarily true. You can easily eval the whole thing, and die with, e.g. "'Some value' illegal value for property 'bar'". Though I'm not making an argument about whether or not chaining setters is a good practice.

Re:chaining

TheNomad on 2006-06-19T22:08:26

Good point!

But it sort of sounds like an argument for design by contract.

Oh btw, thanks to the two so far who have left a comments on my first over post! :)

Re:chaining

Alias on 2006-06-20T02:49:42

If you are chaining methods you have to do error via exceptions.

Chaining Accessors

davorg on 2006-06-20T10:37:16

I think you want Class::Accessor::Chained.

Re:Chaining Accessors

TheNomad on 2006-06-21T07:00:39

Thanks perfect!

I haven't made up my mind whether accessors that return the object are such a good idea. Say, for example, you have some basic code:

package DoStuff;
.... code to make accessors goes here. We have get_foo and set_foo.

sub make_foo_value {
$self = shift;
$self->set_foo(rand)

}

package main;

my $stuff = DoStuff->new;
$stuff->make_foo_value;

What should make_foo_value return? If it returns $self, then you need to go:

print $stuff->make_foo_value->get_foo;

On the other hand, if it returns the value you just set, you go:

print $stuff->make_foo_value;

What is better? Trying to make these sorts of decisions does my head in :)