in reply to Re: Class attribute get/set approach flaws?
in thread Class attribute get/set approach flaws?
Not necessarily true. It can actually make code easier to work with.
my %validation_for = ( foo => qr/^\d+$/, # foo must be an integer bar => \&validate, }: sub attr { my ( $self, $attr ) = splice @_, 0, 2; croak "No such attribute $attr" unless exists $validation_for{$attr} +; return $self->{$attr} unless @_; # set the value my $validation = $validation_for{$attr}; my $new_val = shift; if ('Regexp' eq ref $validation) { croak "$new_val doesn't match $validation" if $new_val !~ $validation; } else { $self->$validation($new_val); # we'll assume it throws an error } $self->{$attr} = $new_val; return $self; }
With that quick hack, adding a new attribute is as simple as adding a new key/value pair to the validation lookup.
You can then use a single method for getter/setters for everything and still have validation. Whether or not that's appropriate for your needs depends on your requirements. Also, "extra" behavior can easily be added to the validation subroutine, though at that point you'd probably want to rename the hash.
Cheers,
Ovid
New address of my CGI Course.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Class attribute get/set approach flaws?
by sauoq (Abbot) on Nov 28, 2005 at 23:48 UTC | |
by diotalevi (Canon) on Nov 28, 2005 at 23:54 UTC | |
by sauoq (Abbot) on Nov 29, 2005 at 01:34 UTC | |
by diotalevi (Canon) on Nov 29, 2005 at 01:37 UTC | |
by sauoq (Abbot) on Nov 29, 2005 at 02:55 UTC | |
|