PHP:Write Clean Logic Statements
Monday, June 30th, 2008Example 1: Unclean Conditional Logic
<?php
if($userLoggedIn) {
// Hundreds of lines of code
}else{
exit();
}
?>
The above statement seems straight forward, but it’s flawed for the reason that the developer is giving this conditional block too much responsibility. I know that might sound a little weird, but stay with me.
The type of conditional organization above makes for unnecessarily complex code to both interpret and maintain. A brace that’s paired with a control structure hundreds of lines above it won’t always be intuitive for developers to locate. I prefer the style of conditional logic in example 1.2, which inversely solves the previous example. Let’s take a look.
Example 2: Clean Conditional Logic
<?php
if(!$userLoggedIn) {
exit();
}
// Hundreds of lines of code
?>
This conditional statement is more concise and easier to understand. Instead of stating: “if my condition is met, perform hundreds of operations, else exit the script”, it’s saying “if my condition is not met, exit the script. Otherwise, I don’t care about what happens after that. I am only concerned with stopping execution”. So, by doing this, you’ve limited the operations that a given control structure has been tasked with, and that will help other developers quickly understand your code.