Re: Assertions

From: Date: Thu, 17 Oct 2013 17:03:37 +0000
Subject: Re: Assertions
References: 1 2 3 4 5 6 7 8 9 10  Groups: php.internals 
Request: Send a blank email to internals+get-69641@lists.php.net to get a copy of this message
On Thu, Oct 17, 2013 at 12:12 PM, Nikita Popov <nikita.ppv@gmail.com> 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!

« previous php.internals (#69641) next »