in reply to Re^2: Thoughts on new 'class' OO in upcoming perl
in thread Thoughts on new 'class' OO in upcoming perl
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Thoughts on new 'class' OO in upcoming perl
by Jenda (Abbot) on Apr 10, 2023 at 11:20 UTC | |
by tobyink (Canon) on Apr 10, 2023 at 15:14 UTC | |
by haj (Vicar) on Apr 10, 2023 at 21:11 UTC | |
by choroba (Cardinal) on Apr 10, 2023 at 22:03 UTC |