Techniques to Cut Down on Errors and Bugs


Techniques to Cut Down on Errors and Bugs

When you are programming, there are a few techniques that will help you to cut down on errors in general.

  • Plan

    Before you start any large project, you should always plan the different steps of that project. Going into the project, you should at least know what technology is needed and have a rough sketch of the events that are going to happen. It also helps to diagram the different uses of your program and the errors that could occur in order so that your program has fewer bugs in the long run.

  • Reverse testing

    Reverse testing is the idea of putting the value first ”rather than the variable ”when testing for equality. Consider the following:

     <?php if ($some_variable = 5) {     print "5 matches $some_variable"; } else {     print "5 no match, me cry!"; } ?> 

    As you can see, there is a bug in the if conditional. Instead of testing for equality, we assign the value of 5 to some variable. However, if you run this script, PHP will not report that anything has gone awry. Therefore, to generate error messages, you must reverse the sequence of the test:

     <? if ( 5 = $some_variable) {     print "5 matches $some_variable"; } else {     print "5 no match, me cry!"; } ?> 

    This snippet would generate a warning. You would then correct the error that caused the warning and the final, correct version of the snippet would look like this:

     <? if ( 5 == $some_variable ) {     print "5 matches $some_variable"; } else {     print "5 no match, me cry!"; } ?> 
  • error_reporting

    When testing your script, set error_reporting to E_ALL so that all errors are reported to you, and you know everything that is going on with your script. You can set error_reporting to E_ALL either by the error_reporting() function

     error_reporting(E_ALL); 

    or by setting it your php.ini file.

  • Breakpoints

    When you are debugging your scripts, it is often useful to set breakpoints at which you dump all relevant information going into and coming out of the different parts of your script. Examine the following:

     <?php $var1 = 10; print "the value of var1 is $var1 before somefunc()"; // Breakpoint somefunc($var1); print "now the value of var1 is $var1"; // Breakpoint function somefunc (&$var) {     $var = 20; } ?> 

    Notice how we print out the value of 5 before somefunc() and then after somefunc() . This lets us know whether somefunc() is doing its job. Setting breakpoints like this one can often help you narrow down where a problem is located.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net