I've received a lot of exceptions from QA due to incomplete data being fed to my Moose constructors. The attribute name is present in the constructor arguments, but the value is undef
.
It's a fact of life with many scripting applications that things are just undef
. And oftentimes this is perfectly fine. You don't want an annoying warning from the warnings
pragma (so you do no warnings 'uninitialized'
), and you certainly don't want your code to die because one little value, say the housenumber, is undef
.
So without further ado, I want my Moose constructors to behave like straight Perl (i.e. without use warnings 'uninitialized'
), which is to convert undef
to 0
or the empty string as required. The attempt shown in this sample does not work for the case where the attribute name is present but the value is undef
. I could think of using BUILDARGS
to achieve what I want. But is there a declarative way in plain Moose without resorting to MooseX::UndefTolerant (which unfortunately I cannot use as it is not installed)?
package AAA;
use Moose;
has 'hu', is => 'ro', isa => 'Str';
has 'ba', is => 'ro', isa => 'Int';
no Moose; __PACKAGE__->meta->make_immutable;
package BBB;
use Moose; extends 'AAA';
has '+hu', default => ''; # don't want to die on undef
has '+ba', default => 0; # idem
no Moose; __PACKAGE__->meta->make_immutable;
package main;
use Test::More;
use Test::Exception;
# Those AAAs should die ...
throws_ok { AAA->new( hu => undef ) }
qr/Validation failed for 'Str' with value undef/;
throws_ok { AAA->new( ba => undef ) }
qr/Validation failed for 'Int' with value undef/;
# .. but these BBBs should live:
lives_ok { BBB->new( hu => undef ) } 'hu supplied as undef';
lives_ok { BBB->new( ba => undef ) } 'ba supplied as undef';
done_testing;
(defined($value))
Also, you could installMooseX::UndefTolerant
locally to some directory$my_dir
anduse lib($my_dir);
– Tomtomacommon::sense
. I agree with the author Marc Lehmann in his discussion of uninitialized values. (There are exceptions, but hey - they're exceptions.) Checking the values beforehand is just cumbersome. I'd have to repeat the checks in many places and I try to stay DRY. – Ralph