note 80585 rejected from function.assert by danbrown

From: Date: Mon, 21 Jul 2008 03:55:18 +0000
Subject: note 80585 rejected from function.assert by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-142404@lists.php.net to get a copy of this message
Note Submitter: stangelanda at gmail dot com ---- With all the discussion of how to best to use assert, I thought I would put my two cents in. I feel that errors should be thrown for potential things that could go wrong in production like failed database connections, but asserts should be used for sanity checks that should never fire unless there is an actual bug in the code. When writing difficult code I use asserts to check for hard to find mistakes like unexpected race conditions. Then I leave them on (but logging only of course) in production. My assert statements tend to be very computationally cheap. In fact generally my assert statements are as simple as checking the return value from boolean functions. This means I generally end up with alot of code like the following: <?php $result = flock($file, LOCK_EX); assert('$result'); $result = ftruncate($file, 0); assert('$result'); $result = fclose($file); assert('$result'); ?> I recently realized that I could write the much cleaner: <?php flock($file, LOCK_EX) or assert(0); ftruncate($file, 0) or assert(0); fclose($file) or assert(0); ?> Much cleaner. Of course the error message doesn't tell me anything about the failure like it does when you pass a string. But an assertion failing means I have a major bug in my code, so its not too much work to look up the line number and figure out the error. Also note that I don't use this for every boolean statement, since sometimes a failure isn't cause for an error. For example when I create a new user in the database, if the query fails its not an error, it just means the username is taken. If I did an assert there it would have to check that the query was successful or the mysql_errno was what I anticipated. But I could do that as follows: <?php mysql_query("INSERT INTO users (username, password) VALUES ('{$username}','{$password}')") or assert('mysql_errno()===1061'); ?>

« previous php.notes (#142404) next »