LWN.net Logo

Cracks in the Foundation (PHP Advent)

Cracks in the Foundation (PHP Advent)

Posted Dec 18, 2011 22:05 UTC (Sun) by alankila (subscriber, #47141)
In reply to: Cracks in the Foundation (PHP Advent) by Richard_J_Neill
Parent article: Cracks in the Foundation (PHP Advent)

So you are saying that 0 == strpos($x, $y) will do the wrong thing when the string is not found at beginning. Other languages show remarkably more sense by returning -1 or something. Sorry, but this specific example you picked is full of fail.


(Log in to post comments)

Cracks in the Foundation (PHP Advent)

Posted Dec 21, 2011 2:37 UTC (Wed) by Richard_J_Neill (subscriber, #23093) [Link]

Perhaps using strpos() wasn't quite such a good example, because -1 could never be a valid answer, and is therefore potentially OK as an error-flag.
This is in the same spirit as, for example, C's write() .

BUT, what do you do with an integer-function that normally returns an integer (negative, positive, or zero) when it needs to return an error?

There are several ways to do it; of which I think that C's strtol() is the worst possible. Some might suggest returning an object, but that's logically equivalent. PHP has adopted the general convention that any function that fails will return false; I think this is actually quite sensible once one knows to expect it.

As for the casting rules of "0.0" vs 0.0, it's rather a perverse example, which shouldn't happen in real-life.

Cracks in the Foundation (PHP Advent)

Posted Dec 21, 2011 4:26 UTC (Wed) by nybble41 (subscriber, #55106) [Link]

> BUT, what do you do with an integer-function that normally returns an integer (negative, positive, or zero) when it needs to return an error?

Return success or failure (or a more specific error code), and store the result in a reference parameter? That's the standard C approach. If the possibility of failure exists, you'll need to check for that first anyway before using the result. For uncommon failure modes, in languages which support it, alternate continuations (including, but not limited to, C++-style exception handling) offer a more efficient solution.

> PHP has adopted the general convention that any function that fails will return false; I think this is actually quite sensible once one knows to expect it.

That's great so long as you don't need to return false in a non-failure situation... The Common Lisp solution to this is rather elegant: return two values, the first being the result or false, and the second (which you can ignore) indicating success or failure. If you know that successful results can't be false you can use the normal return value, but the extended status is there if you need it.

Copyright © 2013, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds