[Chicago-talk] undef and Moose types

Andrew Rodland andrew at cleverdomain.org
Fri Apr 29 06:37:39 PDT 2011


On Thursday, April 28, 2011 05:00:36 PM Sean Blanton wrote:
> When you have a constructor and it fails, It's not common practice to
> return a "null" object. Perl modules usually return undef.
> 
> However, in Moose, in a Moose role that I want to do this:
> 
> has ssh => (
> is      => 'rw',
> isa     => 'Net::SSH2',
>  default => \&ssh_builder,
> lazy    => 1,
> );
> 
> ---
> 
> To use this within a class, I do this:
> 
> my $ssh = $self->ssh;
> $log->warn("couldn't connect") unless defined $ssh;  #-- this line for
> illustration
> 
> ---
> 
> So, I want to handle any errors such as when \&ssh_builder fails and
> returns 'undef', but what happens is that it crashes before the error
> handling code because 'undef' is not of type 'Net::SSH2'. So what I do to
> fix it is take out the 'isa     => 'Net::SSH2',' from the definition of
> the 'ssh' attribute.
> 
> Now I lose the advantage of having the type check in my development for the
> 99.99% of the time when there are no errors. It seems to me that 'undef'
> should be considered to be a member of every class, or better yet have an
> option to make it so.  Is there another way of getting the advantages of
> the type checking and also handling exceptions like this?
> 
> Thanks,
> Sean

There's a parameterized type in the default Moose type library called "Maybe" 
that deals with this -- isa => "Maybe[Net::SSH2]" will allow in Net::SSH2 or 
undef -- you can read more in the Moose::Util::Typeconstraints.

That really strikes me as wrong, though. An attribute initializer *should* die 
if the builder isn't able to provide the resource that the attribute is 
supposed to hold. If you want to provide error handling for ssh object 
lazybuild, then I'd consider writing a method that does something like

sub ssh_safe {
	my $self = shift;
	return try {
		$self->ssh
	} catch {
		...
	}
}

but that's just my first impression.

Andrew


More information about the Chicago-talk mailing list