Andreas Heigl wrote on 22/03/2016 16:25:
In the PHP 7 and typing presentations I've been giving[1], I've advocated
either:
>
>1) Throw an exception if the rest of the code is going to break anyway.
>2) Define an empty object with matching interface if you want an equivalent of
0/empty string.
When code expects a user-object but can't get one it'll break. Throwing an
exception makes it easy to react to that. But when the code has to check
whether that's a mocked user object or a real user object it's about as good as
returning null or eliminating the return type altogether as you have to build
the code around that returned value you can't really use.
It depends on the context; sometimes, you are right, you would end up
checking for validity early anyway, and an exception would be easier.
However, the Null Object Pattern can simplify logic significantly where
there is an obvious "null behaviour" that it can implement.
Wikipedia gives the example of a recursive tree operation having to
check for missing child nodes
(https://en.wikipedia.org/wiki/Null_Object_pattern#Example);
initialising the child nodes with Null Objects eliminates the check.
The key point is that in some cases, the calling code *won't* break,
because the Null Object can still adhere to the interface, just by
returning appropriate empty values. In the tree node case, a
NullTreeNode would always return further NullTreeNodes as children, a
sub-tree size of 0, and either no-op or error if you attempted modification.
Regards,
--
Rowan Collins
[IMSoP]
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php