in reply to Re: Re: Re: Autoboxing: Yes or No?
in thread Autoboxing: Yes or No?

That sounds like a good use of the Null Object pattern.

Replies are listed 'Best First'.
Re: Re: Re: Re: Re: Autoboxing: Yes or No?
by mirod (Canon) on Jan 01, 2004 at 21:35 UTC

    I thought about that, and even experimented with it, but if I use a Null Object I cannot write if( $elt->first_child) {...} anymore, I have to explicitely test for $elt->first_child->is_not_null everywhere, which I don't like, or I have to overload the boolean-ification of the objects, but I am not a fan of overloading, mostly for performance reasons.

    I agree that what I ask for is syntactic sugar, but I think it is also quite a natural way to write code, so it might make sense to have this in the language. I like the idea of undef being the null object. Being able to have a false blessed reference would actually be even better, because in this case I would know to which class that flase value belongs.

      mirod wrote: If I use a Null Object I cannot write if( $elt->first_child) {...} anymore.

      Ovid begs to differ :)

      package Null::Object; use overload 'bool' => \&bool; my $self; sub new { $self ||= bless {}, shift } sub AUTOLOAD { $self } sub bool { return; } package main; my $null = Null::Object->new; $null->foo->bar->baz; if ($null) { print "We shouldn't be here!"; } else { print "We are false!"; }

      That might need a bit of tuning, but you get the idea.

      Update: I just noticed that you mentioned overload, so my bit of code is not news to you :) On the other hand, if clean null objects is the only benefit of autoboxing, then I again can't see much of a benefit to them. I might also add that null objects should be the exception rather than the rule, thus the performance impact should be minimal (I hope).

      Cheers,
      Ovid

      New address of my CGI Course.

        Ovid this is very interesting... can you explain when you would use this? I've been reading the refactoring book, and like the idea of null objects, but I cannot wrap my brain around your post. Would you put this in the inheritance tree of all objects? Where would one put in the correct behavior for say a Null DBI connection or a Null EmployeeAddress or whatever?

        Thanks for clarifying this for me and all --

        rkg

        I might also add that null objects should be the exception rather than the rule, thus the performance impact should be minimal (I hope).

        I haven't benchmarked overloading in a while, but as far as I remember, just using it caused quite a huge performance hit in the rest of the code. IIRC something like 30% slower, with 5.6.0. Things might have changed since then though.