On Dec 10, 2014, at 4:12 PM, Christoph Becker <cmbecke...@gmx.de> wrote:

> Josh Watzman wrote:
> 
>> However, for a lot of failures, I don't feel that exceptions are
>> appropriate. I tend to only use them for exceptional behavior --
>> usually, some failure that needs to be propagated up a few levels up
>> the stack, to an appropriate error boundary. This doesn't necessarily
>> mean a completely unrecoverable error, but it's *locally*
>> unrecoverable. For things that are completely recoverable, returning
>> null might be more appropriate and more lightweight, and then this
>> nullsafe operator would be useful at that point.
> 
> FWIW, there is a third option: instead of returning null, return a null
> object[1].  That causes (slightly) more overhead, but it's quite
> flexible and works rather nicely without requiring the (IMO) ugly ?->
> nor exception handling.
> 
> Consider a non-existent user "foo":
> 
>  User::find('foo')?->getName() // returns null
> 
>  User::find('foo')->getName() // could also return '' or 'Unknown user'

This is actually what the implementation does behind the scenes, but issues 
with this approach actually being visible to userlevel code is what prompted 
the feature in the first place :) The biggest problem is that you can 
accidentally leak your null object, which causes the calling code to 
unexpectedly swallow errors; with the ?-> operator, you know you're always 
immediately using the null object, there's no way to hold onto it. Smaller 
problems are that you either need a different null object for every object you 
want to use this with, or a single general one with __call, which is ugly and 
hard to optimize. It's also impossible to typecheck, but that was a problem for 
Hack and is pretty irrelevant to PHP.

It's also worth noting that doing this with a null object would have the same 
lack of short circuiting that I've been arguing for ;)

Josh


--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to