My take on assertions, which I also tried to stick to in Wikibase, is as 
follows:

* A failing assertion indicates a "local" error in the code or a bug in PHP; They should not be used to check preconditions or validate input. That's what InvalidArgumentException is for (and I wish type hints would trigger that, and not a "fatal error"). Precondition checks can always fail, never trust the caller. Assertions are things that should *always* be true.

* Use assertions to check postconditions (and perhaps invariants). That is, use them to assert that the code in the method (and maybe class) that contains the assert is correct. Do not use them to enforce caller behavior.

* Use boolean expressions in assertions, not strings. The speed advantage of strings is not big, since the expression should be a very basic one anyway, and strings are awkward to read, write, and, as mentioned before, potentially dangerous, because they are eval()ed.

* 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, like Java's AssertionError.


I think if we stick with this, assertions are potentially useful, and harmless at worst. But if there is consensus that they should not be used anywhere, ever, we'll remove them. I don't really see how the resulting boiler plate would be cleaner or safer:

if ( $foo > $bar ) {
    throw new OMGWTFError();
}

-- daniel



Am 31.07.2013 00:28, schrieb Tim Starling:
On 31/07/13 07:28, Max Semenik wrote:
I remeber we discussed using asserts and decided they're a bad
idea for WMF-deployed code - yet I see

Warning:  assert() [<a href='function.assert'>function.assert</a>]:
Assertion failed in
/usr/local/apache/common-local/php-1.22wmf12/extensions/WikibaseDataModel/DataModel/Claim/Claims.php
on line 291

The original discussion is here:

<http://thread.gmane.org/gmane.science.linguistics.wikipedia.technical/59620>

Judge for yourself.

-- Tim Starling


_______________________________________________
Wikitech-l mailing list
Wikitech-l@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/wikitech-l



_______________________________________________
Wikitech-l mailing list
Wikitech-l@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/wikitech-l

Reply via email to