I just chanced upon Simplified attribute accessors using overloading. It's a reinvention of the common Perl 5 idiom of having a single method for accessing and mutating an objects state.
$value = $object->field_name; # get value $object->field_name($value); # set value
in Python!
def givenName(self, value=omitted): if value is not omitted: self._givenName=value return self._givenName
In Perl5 you would do it something like this:
sub givenName { my $self = shift; $self->{_givenName} = shift if @_; return $self->{_givenName}; };
In Perl 6 (assuming I've managed to remember all that Exegesis and Apocalypse stuff) you could do it with multi-methods something like this:
multi method givenName (Foo $self) { $self._givenName; }; multi method givenName (Foo $self, $value) { $self._givenName = $value; };
Which is nice, since we completely separate the accessor / mutator code. Alternatively if you want it all wrapped up in a single subroutine you could use an optional argument:
method givenName ( ?$value ) { defined $value ? $._given_name = $value : $._given_name; };
(is it possible to tell the difference between an optional value that isn't supplied and an optional value passed as undef in Perl 6?)
I know some people dislike the idiom and prefer the extra clarity of separate accessor/mutator method names - but I still think this is cute ;-)
In reply to Single accessor/mutator idiom in Perl5, Perl6 and Python by adrianh
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |