Home arrow PHP arrow Page 2 - Debugging and Performance

Flattening if Statements - PHP

Debugging is an important part of coding. One way to make the debugging process easier is to write quality code to begin with. This article, the first of two parts, will point out some of the most common coding errors, and help you identify problems in your code. It is excerpted from chapter 12 of Zend PHP Certification, written by George Schlossnagle et al (Sams; ISBN: 0672327090).

TABLE OF CONTENTS:
  1. Debugging and Performance
  2. Flattening if Statements
  3. Splitting Single Commands Across Multiple Lines
  4. One Equal, Two Equals, Three Equals
  5. Testing for Resource Allocation
By: Sams Publishing
Rating: starstarstarstarstar / 9
November 22, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Consider the following snippet of code:

if ($is_allocated) 
{
if ($has_been_mangled) 
{
if ($foo == 5) 
{
print "foo is 5";
} 
else 
{
print "You entered the wrong data!";
}
} 
else 
{
return false;
}
}
else 
{
return false;
}

As you can see, the many nested if statements here cause the code to look very busy and difficult to read. An easy way to improve the situation consists of "flattening" your if statements so that you can achieve the minimum level of indentation without compromising either the functionality of your code or its performance. The preceding script, for example, could be rewritten as follows:

if (!$is_allocated) 
{
return false;
}
if (!$has_been_mangled) 
{
return false;
}
if ($foo == 5) 
{
print "foo is 5";
} 
else 
{
print "You entered the wrong data!";
}

This approach gives you a better structure with fewer levels of nesting so that your code is easier to understand. Note that the type of operations performed is pretty much the same as before—and the elimination of two else statements will make the code easier to parse for the interpreter.



 
 
>>> More PHP Articles          >>> More By Sams Publishing
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: