Small Changes to Make If Statements Easier to Scan

When developing programs with hundreds of lines of code, it's beneficial to write code that's easy to scan. That way when you're updating the program months or years later, it will be much easier to follow along. In addition to breaking the code into logical chunks, adding comments, etc., it's helpful to indent code which only gets executed given a specific criteria…such as code that's within an if/else statement.

Example

Let's say we have a page which displays an HTML form when the visitors first arrive. It then displays a thank you message once the form is submitted. The code could be written out as follows:

<?php
if(isset($_POST['submit'])) {
$first_name = trim($_POST['first_name']);
$last_name = trim($_POST['last_name']);
echo "Thank you $first_name $last_name, your information was received on ";
echo date('F j, Y');
} else {
echo '<form method="post" name="form" action="">';
echo '<label for="first_name">First Name:</label> ';
echo '<input type="text" name="first_name" id="first_name" /><br />';
echo '<label for="last_name">Last Name:</label> ';
echo '<input type="text" name="last_name" id="last_name" /><br />';
echo '<input type="submit" name="submit" value="Send Info" />';
echo '</form>';
}
?>

But is there anything we can do to improve the code? It's somewhat difficult to determine where the "if" ends and the "else" begins. So how does it look if we indent the lines of code within the if/else.

<?php
if(isset($_POST['submit'])) {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    echo "Thank you $first_name $last_name, your information was received on ";
    echo date('F j, Y');
} else {
    echo '<form method="post" name="form" action="">';
    echo '<label for="first_name">First Name:</label> ';
    echo '<input type="text" name="first_name" id="first_name" /><br />';
    echo '<label for="last_name">Last Name:</label> ';
    echo '<input type="text" name="last_name" id="last_name" /><br />';
    echo '<input type="submit" name="submit" value="Send Info" />';
    echo '</form>';
}
?>

Conclusion

Now that's much easier to scan. Of course, you could adjust the number of spaces to indent each line of code. Instead of five spaces, like above, maybe you prefer a bigger or smaller indent.

Related Posts

0 Comments

There are currently no comments.

Leave a Comment