develooper Front page | perl.moose | Postings from July 2008

Re: checking consistency between attributes

Thread Previous | Thread Next
From:
charlie
Date:
July 14, 2008 18:24
Subject:
Re: checking consistency between attributes
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 <Guillaume.Rousse@inria.fr>
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




Thread Previous | Thread Next


Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About