Hi,
On Wed, Jul 31, 2013 at 10:36:56AM +0200, Daniel Kinzler wrote:
- Use boolean expressions in assertions, not strings.
I do not agree that this is best practice in PHP.
Execution time being only part of argument here. Among other arguments are readability of the error message. When using strings, the error message contains the condition of the failed assertion.
But as has been pointed out by other posts in this thread, correct quotation of the string is obviously crucial.
The speed advantage of strings is not big, since the expression should be a very basic one anyway, [...]
They should? In practice they typically are not. For example
assert( $this->indicesAreUpToDate() );
of WikibaseDataModel/DataModel/Claim/Claims.php boils down to nested looping, if I read the code correctly. But (leaving the question aside whether that part is misusing assertions) using complex predicates is totally ok (and even useful) when putting them in strings, as the expression would not get evaluated in production anyways.
- The notion of "bailing out" on "fatal errors" is a misguided remnant
from the days when PHP didn't have exceptions. In my mind, assertions should just throw an (usually unhandled) exception
We could get that by adapting assert_options ...
, like Java's AssertionError.
That comparison is ill suited. Java's AssertionError is a java.lang.Error and not java.lang.Exception. And thereby it's clear what the Java world thinks about catching assertion failures [1]:
An Error [...] indicates serious problems that a reasonable application should not try to catch.
But then again… maybe that was what you meant by “usually unhandled” anyways.
I don't really see how the resulting boiler plate would be cleaner or safer:
if ( $foo > $bar ) { throw new OMGWTFError(); }
Totally! It looks even less clean to me, as after such guards only the negated condition holds. So (when not misusing them) asserts are a way to reduce complexity of reading code.
Best regards, Christian
[1] http://docs.oracle.com/javase/7/docs/api/java/lang/Error.html but this intepretation stands since around Java 1.4 and has proven useful.