Spiga

Three Quick Tips To Make Your PHP Understandable

Producing code that clearly conveys a developer's intent is key to any well written application. That not only applies to PHP, but every programming language. Developers who emphasize the creation of legible code tend to create applications which are easier to both maintain and expand upon. After seven years of programming in PHP I've worked on a variety of projects where well organized and legible code were set aside for numerous reasons. Some of those reasons include time constraints, lack of experience, lost enthusiasm, misdirected pre-optimizing, and the list goes on.

Today we'll look at three simple methods which are commonly ignored by developers for some, if not all of the reasons described above. First, we'll discuss the importance of clean conditional logic. Second, we'll look at how you can cleanly output blocks html of in PHP. And finally, we'll examine the use of sprintf to convey variables placed in stings more legibally.

Tip #1: Write Clean Logic Statements

Example 1.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 1.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.

Read More

0 comments: