Debugging and Performance - Flattening if Statements
(Page 2 of 5 )
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.
Next: Splitting Single Commands Across Multiple Lines >>
More PHP Articles
More By Sams Publishing
|
This article is excerpted from chapter 12 of Zend PHP Certification, written by George Schlossnagle et al (Sams; ISBN: 0672327090). Check it out today at your favorite bookstore. Buy this book now.
|
|