http://www.perlmonks.org?node_id=1006461


in reply to Re: Moose "unions" and inheritance
in thread Moose "unions" and inheritance

Hello tobyinc.

So, I forgot '+' and used subtypes.

package KeyAtom; use Moose; use Moose::Util::TypeConstraints; subtype 'typeKeyAtom', as 'Str | RegexpRef'; has 'data' => ( is => 'rw', isa => 'typeKeyAtom', ); package ValAtom; use Moose; use Moose::Util::TypeConstraints; extends 'KeyAtom'; subtype 'typeValAtom', as 'typeKeyAtom | ArrayRef | HashRef'; #has 'data' => ( #oh my... has '+data' => ( is => 'rw', #re declare isa => 'typeValAtom', ); no Moose; ###test package main; use Data::Dumper; my $test= ValAtom->new(); for ("test str", qr("^test"), [qw/a b c/], {a=>'b',b=>'c'}, sub{'test' +} ){ $test->data($_); print Dumper $test->data; }
So I read again Moose::Manual::Attributes and found statement ...

We recommend that you exercise caution when changing the type (isa) of an inherited attribute.

I would like to ask what is "caution" here?

Replies are listed 'Best First'.
Re^3: Moose "unions" and inheritance
by tobyink (Canon) on Nov 30, 2012 at 12:24 UTC

    "I would like to ask what is "caution" here?"

    package Person { use Moose; has name => (is => 'ro', isa => 'Str'); sub introduce_yourself { my $self = shift; printf("My name is %s\n", $self->name); } } package SecretAgent { use Moose; extends 'Person'; # secret agents have many aliases has '+name' => (isa => 'ArrayRef'); } my $bond = SecretAgent->new( name => ['James Bond', 'Burt Saxby', 'David Somerset'], ); $bond->introduce_yourself;

    You see the problem?

    Making a type constraint tighter (e.g. if the parent class wants a Num, and the child class restricts it to an Int) should usually be just fine. Making it looser requires more caution. The author of the SecretAgent class needs to check which methods of Person assume that name is a string, and override them all.

    package SecretAgent { use Moose; extends 'Person'; # secret agents have many aliases has '+name' => (isa => 'ArrayRef'); sub introduce_yourself { my $self = shift; my @names = @{ $self->name }; my $name = $names[ rand @names ]; my $surname = (split / /, $name)[-1]; printf("The name's %s, %s\n", $surname, $name); } }
    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

      Thanks for good example and clear explanation...

      So, all methods of Person using name attribute get troubled.

      At first I thought "around" at SecretAgent will work somehow, but "name" is already overrided and it is "ArrayRef" at Person's introduce_yourself method.

      This is really caution for me.