Wise Brothers, I seek you advice.
I am working on a Moose based class, that is to have a set of mutually exclusive boolean attributes. (Think radio buttons in a web form).
The attributes represent status, which can be 'success', 'error', 'pending' or undefined.
I have currently implemented this in Moose with one attribute that holds status, and a number of old style access methods to get and set the value:
package MyCompay::Result; use Moose; has '_status' => ( is => 'rw', isa => 'Str', ); sub success { my($self, $arg) = @_; if( defined $arg ) { $self->_status( (!!$arg) ? 'success' : undef ); } return ( 'success' eq $self->_status() ); } sub error { my($self, $arg) = @_; if( defined $arg ) { $self->_status( (!!$arg) ? 'error' : undef ); } return ( 'error' eq $self->_status() ); } sub pending { my($self, $arg) = @_; if( defined $arg ) { $self->_status( (!!$arg) ? 'pending' : undef ); } return ( 'pending' eq $self->_status() ); } 1;
The thing is, the code above is quite long and repetitive, which is just the sort of thing that Moose is designed to avoid. There is also nothing on the _status attribute to prevent something accessing it directly and setting it to an invalid value
Is there a more efficient way to achieve the same result? Can I declare virtual fields in Moose, and provide reader and writer methods, that just test or change the value of _status? Can I put guard on the _status field to enforce it's value so that it acts as an enum?
In reply to Moose: mutualy exclusive bolean attributes. by chrestomanci
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |