in reply to Moose: return null object

Hmm. Seems to me that the purpose of new is to create an object. I would expect any object creation that failed would throw an exception, so I would think that the previously suggested:

my $obj = eval { Class->new($whatever) }; if (not $obj) { do_something_else(); }
would be the way to go. Obviously, there are different opinions, or this question would not have arisen.

Another possibility would be to define another class method, say maybe_create(), which would wrap up an eval'd new(). That way you could have your optional object creation without violating the sanctity of the "new() returns an object or dies" idea.

Replies are listed 'Best First'.
Re^2: Moose: return null object
by Anonymous Monk on Jul 02, 2015 at 11:43 UTC
    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.
      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.