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.
blog comments powered by Disqus |
|
|
|
|
|
|
|