On Oct 20, 2014, at 3:57 PM, Andrea Faulds <a...@ajf.me> wrote: > Good evening, > > I am presenting a new RFC to add a set of three functions to do validated > casts for scalar types: > > https://wiki.php.net/rfc/safe_cast > > Please read it. > > Thanks!
I think this is pretty cool, but I'm really worried about some of its typing implications. In particular: > The functions return FALSE on failure instead of NULL because: Throwing an exception or even returning NULL seems so much better than returning "false" -- "false" is a boolean, not an error, and despite some historical cases of PHP using "false" as a poor person's error code, it really isn't. If you want error codes, use error codes, or use exceptions, but having two kinds of failure, null vs false, is really confusing. Addressing your arguments one by one: > • If strict type hinting were added, they would fail for a nullable > typehint Throwing an exception also addresses this, in a much cleaner way. If you're worried about strict typing, then returning "false" is even worse, since the return type of, for example, to_int is now "int | bool" as opposed to "nullable-int" or "int" (if you throw). > • FALSE is a traditional error value in PHP Since this is a new function, one that doesn't interoperate in any complicated way with the existing library or affect BC, this doesn't seem that important. IMO a language should have one failure/absense-of-value, in most cases "null", and having a weird second case seems, well, weird. If you have more interesting failure cases, just throw an exception, or return null if you want, don't continue propagating a weird second kind of null (that isn't actually null, it's a boolean false). Also, that we *couldn't* introduce a meaningful to_bool function, even if we decided we wanted it, indicates to me that returning false is the wrong thing to do. > • NULL is used to signify the absence of a value - but what we want to > signify is an invalid value (similar to 0 vs NaN) I might argue that failure is indeed absense-of-value, but an exception seems like a much better way to convey this. It's also interesting to look at how other languages handle failures of this kind. Most imperative languages I know of either throw or return null; in particular, Python, which has fairly similar type system to PHP in a lot of ways, throws. Functional languages do more interesting things; Haskell does something complicated but morally equivalent to returning null. But I'm not aware of any language which specifically returns false. -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php