On Thu, Oct 17, 2013 at 12:12 PM, Nikita Popov <[email protected]> wrote:
> I would greatly appreciate a more detailed explanation as to how these
> examples abuse assertions.
All three use the failure of an assertion to alter the flow of
execution of the program. Essentially you wrote, "Nobody is arguing
that assertions should be used as a control-flow structure" and then
provided three examples of using assertions to do exactly that.
All three cause unexpected behavior if the asserted condition is not
true and assertions are disabled because the condition was not
evaluated.
In all three of those examples, the behavior you want is easily
obtained by throwing an exception.
In fact, what some people might do in those situations is:
assert($myObject->internalState == OBJECT_STATE_VALID, "internal
object state not valid");
if ($myObject->internalState != OBJECT_STATE_VALID)
throw FMLException("internal object state not valid");
(In this case, you would probably do the PHPUnit stuff with assertions
disabled.)
Assertions are a debugging/development check designed to facilitate
proof of correctness. They are not present or used in production
code. There is no danger that a failed assertion will ever cause a
production app to abort. They serve one purpose, which is to bring
things to a screeching halt when somethat that should never, ever
happen has happened. And their value comes *because* they are
independent of methods used to handle potentially-recoverable errors.
Why do we need a new way to throw an exception?
Why do we need to mess up another tool that has a different purpose to do it?
What's wrong with writing the three-line function one time to get the
behavior you want?
It's totally reasonable to tie in to the stack-trace generating code
to provide as much information as possible about why an assertion
failed, similar to what exceptions do. But assertions must not be
catchable through any normal mechanism, and the minute code execution
resumes after a check fails, that check is absolutely a control-flow
structure, and it is not an assertion.
Thanks!