How do you prevent your OO system from throwing in case a mandatory parameter is missing and convince it to return undef instead?
How do you prevent bless() from throwing in case a mandatory parameter is missing, and convince it to return undef instead?
my $data = undef;
my $object_or_undef = bless( $data, 'My::Class' );
(The above will throw an exception.)
The answer is you don't even try to stop bless bless from throwing. You wrap it in sub new { ... } so you have more control over how bless is called:
package My::Class {
sub new {
my ( $class, $data ) = @_;
return undef unless ref $data eq 'HASH';
bless $data => $class;
}
}
my $data = undef;
my $object_or_undef = My::Class->new( $data );
Similarly, if you don't want core OO's new to throw an exception when mandatory paramaters are missing, you wrap it in another method.