Blog post7 PHP code misuses

7 problems that might prevent your PHP code from being awesome

Published March 26, 2015

One of the main challenges faced by both beginners and advanced programmers is how to improve their code writing style to make it more readable and maintainable. In this post, you will find a list of 7 typical problems that programmers may face along with the simplest methods to solve these problems. These problems are, in fact, code misuses that are introduced to the code by the programmer himself, and their eradication may greatly improve the readability, maintainability, and usability of the code that the programmer writes.

These problems are, in fact, code misuses that are introduced to the code by the programmer himself, and their eradication may greatly improve the readability, maintainability, and usability of the code that the programmer writes.

Problem #1: Not using functions

Problem: Not using functions is a characteristic problem for PHP programmers, especially early on in their careers. The problem stems from the fact that a programmer can write dozens of lines of PHP scripts without having to wrap the parts of the code in functions. This is problematic because it is difficult to understand what the code actually does without delving deeply into it, and the programmer may repeat himself unintentionally.

Solution: The solution is to divide the code into individual functions.

Problem #2: Not using PHP built-in functions

Problem: We need a function to solve a common problem, and we try to write it ourselves instead of looking for an existing function that provide the functionality that we need.

Solution: PHP offers hundreds of useful functions which eliminate the need to “reinvent the wheel”, and will often do the job much more efficiently than anything that a standard programmer writes. So, if you come across the need to write complex functions that you think may already exist, it is best to search the Internet (and the PHP documentation in particular) before embarking on writing your own code.

Problem #3: Vague names for functions and variables

Problem: Another problem that appears even among experienced programmers is that of vague and incomprehensible variable and function names. For example, a function name like "doSomething" is much too vague. The problem may be due to several reasons: lack of awareness, laziness, or the result of a function that had been written to serve a specific action, but which ended up doing another action instead. This problem contributes to the reduction in code readability and adds to the difficulty in maintaining and modifying the code.

Solution: The solution is to give functions and variables accurate and descriptive names that contain 2 to 3 words or more.

Problem #4: Magic numbers and strings

Problem: A magic number is a number that is found in the code which has no explanation or name. For example, the number 5 in the following code example is a magic number:

<?php
for($i = 0; $i < 5; $i++)
{
  //do check
}

It is unclear why the code should run 5 times.

Solution: To make the code more readable, we better give the variable a descriptive name. For example:

$numberOfChecks = 5;

for($i = 0; $i < $numberOfChecks; $i++)
{
  //do check
}   

Similarly, magic strings are strings that appear in the code without any explanation and, in their case also, it is recommended to set the name of a variable as a descriptive name.

Problem #5: Code duplication

If you find yourself writing the same code over and over again, there is something wrong with your code.

Problem: If you find yourself writing the same code over and over again, there is something wrong with your code. Moreover, when you behave in such a way, you violate one of the most important principles of writing modern code: Do not repeat yourself (DRY). The reason why the DRY principle is so important is simple and practical. Imagine if, after you have finished writing the code, you have to change something. If you’re not fastidious enough and have written the same code more than once, you'll have to make an effort to change the code in several places which can contribute to the emergence of bugs. However, if you make sure you don’t repeat yourself, you will have to change the code in only one place.

Solution: The best way to avoid duplicate code is to wrap the code in functions and then call whatever function you need from wherever you need it.

Problem #6: Functions that do more than one thing

An effective function should ideally do only one thing

An effective function should ideally do only one thing so that we can call it from different places in the code knowing with full confidence that it will only do exactly what it is supposed to do, and nothing else. Therefore, care should be taken that any function you write has only a single responsibility.

In the following example, the function validatePhoneNumberThenWrapInHtml does two things:

  • checks if a string is a valid phone number
  • outputs the phone number or a warning wrapped in html
function validatePhoneNumberThenWrapInHtml($string)
{
  //replace all the non-digit characters
  $onlyDigits = preg_replace('/[^0-9]/','',$string);
  
  // checks if the length of the remaining string 
  // is 7-14 characters long
  $onlyDigitsLen = strlen($onlyDigits);
      
  $isValidPhoneNumber = ($onlyDigitsLen >= 7 && $onlyDigitsLen <= 14);
      
  // a warning if it is not a phone number
  if(!$isValidPhoneNumber) $onlyDigits = "Not a phone number";
      
  // return the phone number wrapped in html
  return "<p>{$onlyDigits}</p>";
}

Let's check the function with a valid and non valid strings:

var_dump(validatePhoneNumberThenWrapInHtml("1-800-123-4567"));
var_dump(validatePhoneNumberThenWrapInHtml("1-800-123-45678910"));

Result
string '<p>18001234567</p>' (length=18)
string '<p>Not a phone number</p>' (length=25)

As we can see, the function validates the phone number and then returns the result wrapped in html. This means that we can't use the function each time we want to check the validity of a phone number since it doesn't return a boolean (true or false) value, but rather returns html. The implication is grave since we'd have to repeat ourselves and write the validation code again and again in every function that needs to check the validity of a phone number. This can introduce duplication in our code, whereas duplication is something that we strive to eliminate (see problem #5).

So a better solution is to separate the function into two functions, each having only a single responsibility. The functions are:

  • validatePhoneNumber that validates phone numbers
  • wrapInHtml that wraps the result in html
function validatePhoneNumber($string)
{
  //replace all the non-digit characters
  $onlyDigits = preg_replace('/[^0-9]/','',$string);
     
  // checks if the remaining string 
  // is 7-14 characters long
  // and return boolean (true/false) value
  $onlyDigitsLen = strlen($onlyDigits);
     
     
  return $isValidPhoneNumber = ($onlyDigitsLen >= 7 && $onlyDigitsLen <= 14);
}
 
function wrapInHtml($string)
{
  // return the string wrapped in html
  return "<p>{$string}</p>";
}
 
// check the 2 functions
$string = "1-800-123-4567";
$isValidPhoneNumber = validatePhoneNumber($string);
var_dump(($isValidPhoneNumber)? wrapInHtml($string) : wrapInHtml("Not a valid phone number"));

Problem #7: Too many nested conditions

Problem: One of the main problems that cause the code to be messy and hard to read is that of too many nested conditions (i.e. an if statement within another if statement).

Consider the following code example:

$string==='m';
 
if($string==='a' || $string==='b')
{
  if($string==='a')
  {
    echo "a indeed";
  }
    
  if($string==='b')
  {
    echo "b";
  }
}
else
{
    echo "x";
}

Result
x

Solution: We can solve the problem of nested conditions by making use of functions and the return command.

For example:

function eliminateNestedConditionals($string)
{
  if($string==='a') return "a indeed";
    
  if($string==='b') return "b";
    
  return "x";
}
  
$string = "m";

echo eliminateNestedConditionals($string);

Conclusion

If you want to further your knowledge on the subject of improving your PHP style of coding by lessening code misuses, google the terms code smells and clean code. And if you know about other examples for code misuses, you are most welcomed to share it in the comments section below.

comments powered by Disqus