note 80585 added to function.assert

From: Date: Wed, 23 Jan 2008 16:24:23 +0000
Subject: note 80585 added to function.assert
Groups: php.notes 
Request: Send a blank email to php-notes+get-135339@lists.php.net to get a copy of this message
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'); ?> ---- Server IP: 64.71.164.2 Probable Submitter: 216.248.100.66 ---- Manual Page -- http://www.php.net/manual/en/function.assert.php Edit -- https://master.php.net/note/edit/80585 Del: integrated -- https://master.php.net/note/delete/80585/integrated Del: useless -- https://master.php.net/note/delete/80585/useless Del: bad code -- https://master.php.net/note/delete/80585/bad+code Del: spam -- https://master.php.net/note/delete/80585/spam Del: non-english -- https://master.php.net/note/delete/80585/non-english Del: in docs -- https://master.php.net/note/delete/80585/in+docs Del: other reasons-- https://master.php.net/note/delete/80585 Reject -- https://master.php.net/note/reject/80585 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#135339) next »