Re: checking consistency between attributes

[email protected]
Newsgroups perl.moose
Message-ID <[email protected]>
How about this:

has 'min' => (
   is => 'rw',
   isa => 'Int',
   default => sub { NEGATIVE_INFINITY },
   trigger => sub {
     my ( $self, $val ) = @_;
     carp "min is > max" unless $val <= $self->max;
   }
);

has 'max' => (
   is => 'rw',
   isa => 'Int',
   default => sub { POSITIVE_INFINITY },
   trigger => sub {
     my ( $self, $val ) = @_;
     carp "max is < min" unless $val >= $self->min;
   }
);

No BUILD needed.  Consistency checked by the triggers whenever min and  
max are set...

Besides defining negative and positive infinity, the only problem I  
see is if both min and max are set at the same time, as in the  
constructor.  I don't know which error you'd get if the object was  
initialized like this:

my $foo = Foo->new(
   min => 1,
   max => -1,
);

Charles Alderman

----- Original Message -----
From: Guillaume Rousse <[email protected]>
Sent: Mon, 14 Jul 2008 23:15:49 +0200
Re: checking consistency between attributes



> Hello list.
>
> What's the best way to check consistency between attributes values ? Is
> there anything better than a dedicated BUILD method, such as:
>
> use Moose;
> use Carp;
>
> has 'min'  => (is => 'rw', isa => 'Int');
> has 'max'  => (is => 'rw', isa => 'Int');
>
> sub BUILD {
>     my ($self, $params) = @_;
>
>     my ($max, $min) = ($self->max(), $self->min());
>     croak "max < min" if defined $max && defined $min && $max < $min;
> }
> -- 
> Guillaume Rousse
> Moyens Informatiques - INRIA Futurs
> Tel: 01 69 35 69 62
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.