in reply to Re: Moose: return null object
in thread Moose: return null object

I too wanted to do this. being very new to Moose, I was a bit disappointed to find I could not easily have new return undef on failure. But there is a way. Use overload to have your object stringify to the empty string, or overload the bool operator so that it is 0, when its invalid. Then you can test it afterwards in the normal way. If you need to print an objects type use ref($x) in the normnal way. Some slightly dd code can result like my $x=Object::new(); $x or $x->printerror(); But you get used to that.

Replies are listed 'Best First'.
Re^3: Moose: return null object
by choroba (Cardinal) on Jul 02, 2015 at 11:58 UTC
    Using constructor without the class parameter
    my $x = Object::new();

    instead of the canonical

    my $x = 'Object'->new;

    means it doesn't bless to its first parameter as usually

    sub new { bless {}, shift }

    which in turn means it doesn't work in child classes, because it always creates the object of the parent class.

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      Superdoc, yes indeed thats true. A typo on my part. Slap wrist!!

      But it doesn't affect the point I was making about a way to (apparently) achieve this simple null return from the new constructor as originally requested.

      Yes, that was a typo and irrelevant to the discussion which is can moose classes return null from constructors? I made my classes have a valid flag, and stringify to "" if this is false, catch all exceptions within moose and this way I am able to use this idiom, in fact it works well. I think Moose should not be so prescriptive, exceptions have their place, and I'll respect your judgement that its a better way to do things, but Moose should not force you to do everything the best way, your best may not be the same as mine. That's my humble opinion in any case.