#native_company# #native_desc#
#native_cta#

Best Practices for Refactoring in PHP

By Kaushik Pal
on October 30, 2014

Overview

Refactoring code is an essential aspect of any programming language and PHP is no exception to this rule. In this article, I will talk about how to refactor PHP code.

Introduction

A developer may consider his code as perfect if it runs successfully without any compile-time or run-time errors. But there is always a scope of improvement in working code and refactoring improves the structure of existing code. The code, if not improved, may hamper the performance of an application considering factors such as memory, speed, reusability, etc.

 

Refactoring techniques can be applied to improve code performance in every programming language. The motive is to restructure the existing code. This should not change the external behavior.

In this article, different forms of PHP code refactoring are shown with live examples running on an Online Compiler. It is suggested that refactoring should be performed as the programming work is being done.

Why Refactor?

Why refactor code if it is working fine?” Code refactoring makes it more universally acceptable. It can then be easily understood by experts as well as naive users. Here are some points which show the need for refactoring:

      • Shows understandable coding procedure

      • The code looks clean.

      • Easy editing of code.

      • Easy to maintain code without effecting how it works.

      • Refactoring is acceptable all over the world.

      • Improves the code design.

      • Bugs can be easily detected which can further avoid other hassles.

      • Ends duplication of code.

      • It helps the program to run faster.

Forms

Suitable name: Rename the variables to make them appropriate and easier to guess their usage in the PHP code.

Listing 1: Sample showing a test script before refactoring. Here, the function name is newFunction and the variable name is val. Here the aim of the variable can’t be guessed correctly by the name given to it.

<html>
<head>
<title>Ranking</title>
</head>
<body>

<!-- Total number of countries in 2014 Asian Games is 45 -->
<?php
   function newFunction($val=9) {
      echo "Rank of India in Asian Games is : $val <br>";
   }

   // rank at Asian Games
      newFunction();
?>
</body>
</html>


Figure 1: Output of the code above shown after compilation

Listing 2: Sample code showing test script after refactoring. Here, the naming convention is changed from newFunction to setRank and variable name from val to rank. These shows the names which can be guessed correctly and make it self-explanatory.

<html>
<head>
<title>Ranking</title>
</head>
<body>

<!-- Total number of countries in 2014 Asian Games is 45 -->
<?php
       function setRank($rank=9) {
          echo "Rank of India in Asian Games is : $rank <br>";
       }

       // rank at Asian Games
      setRank();
?>
</body>
</html>


Figure 2: Output shown above as “Rank of India in Asian Games is 9”

Create functions and sub-functions: When writing functions avoid writing the same code again and again. Functions can be called at appropriate positions. For consistency and improving readability the functions can be divided into sub-functions to make the code more clear.

Listing 3: Sample showing a function in PHP

Here Rank is a function calculating and displaying rank points, p is initial points

function Rank($p) {
    echo 'Points earned :'$p;
    echo 'Fairplay Points' : '$fairgame;
    $rank = $p + $fairgame;
    $finalrank = $rank - $slowoverrate;
    echo 'Final rank points is:' $finalrank;
}

Listing 4: The above given function is refactored and divided into subfunctions.

Here DisplayRankPoints and displayFinalRankPoints are functions calculating and displaying rank points, intpts is the initial points.

function DisplayRankPoints($intpts) {
    echo 'Points earned :$intpnts';
    echo 'Fairplay Points' : '$fairgame;
    $rank = $intpnts + $fairgame;
    displayFinalRankPoints($rank)
}
  
function displayFinalRankPoints($rank)
{ 
    $finalrank = $rank - $slowoverrate
    echo 'Final rank points is: $finalrank"
}

Method Signature: A developer may change the parameters of a function to make it clearer. This may include addition, updating and deletion of function name and its parameters. It is mentioned under the section Refactoring Tool: NetBeans IDE below.

Proper usage of parenthesis: Every developer knows the usage of parenthesis. These are used in conditional statements such as if-else, functions, etc. There are two ways of mentioning parenthesis. Continue with a single way for placing parenthesis in a PHP program to avoid any future indentation issues.

Indentation: The code is easier to understand if indented properly and it should be the same in every module and loop. Example: Give 2-3 spaces while writing any line of code.


Figure 3:
 Showing code indentation

Ways to Write Code

There are different ways to write proper code that preempts the need to refactor the code:

Hierarchy: Code indentation should always be perfect. It helps users in understanding the hierarchy of codes. Example: Indentation is of utmost importance in case of nested if-else and nested loops.

Third Party code: Before implementing third-party code in your current working code, perform analysis and testing. This prevents future code running issues.

Comments: Use single-line and multi-line comments to help users to understand the code and its purpose.

Variable Naming Conventions: Use self-explanatory variable, function and class names.

Function Naming Conventions: Use self-explanatory function and module names.

Class Naming Conventions: Use self-explanatory class names.

Code clarity: Keep the code clear from unnecessary nested loops and variables that were initialized but never used.

Fetching records: While fetching records from the database, it is best to fetch particular field names. Example: use select stdaddress, stdph instead of select * to select student address and student phone from studenttable.

Avoid messy code: While writing code, try to avoid messy code. Follow the above points to write complete, concise and clear line of codes (LOC).

Refactoring Tool: NetBeans IDE

I took a dig into refactoring the PHP code in the NetBeans IDE.

Rename: The naming conventions can be changed in NetBeansIDE by right-click on the variable name and selecting Refactoring as shown below. The options available here for variables are ‘Rename’, ‘Move’, ‘Copy’, and ‘Safely Delete’.


Figure 4: Right-click shows Refactoring feature in NetBeansIDE

After clicking on Rename as shown above, the following can be done for renaming the variable name:


Figure 5: The val variable name can be changed to any self-explanatory variable name.

Replace code with new method 

The code can be replaced with a new method in NetBeans IDE for refactoring. As mentioned above under “ways to write code“, the code must be divided into functions for consistency. Here, refactoring option provides with Introduce method option:


Figure 6: Showing Introduce method option in Refactoring

Other refactoring techniques 

The other refactoring techniques under NetBeansIDE includes Change Method Parameters, Extract Interface, extract Super class, etc. It also shows Introduce Method option:


Figure 7: Some other techniques under refactoring

Refactoring Example

Example is shown below for refactoring simple code.

Listing 5: Code showing if-else-if statement conditions before refactoring

<html>
<head>
<title>Studying status</title>
</head>
<body>
<?php
$tutorial="java";

if($tutorial=="java")
   $result = "Studying Java tutorial";
elseif($tutorial=="php")
   $result = "Studying php tutorial";
elseif($tutorial=="ruby")
   $result = "Studying ruby tutorial";
else
   $result = "Studying Maths";

echo $result;

?>
</body>
</html>


Figure 8: Output is shown above as “Studying Java tutorial”

Here, we can see the refactored code that avoids usage of unnecessary looping. Case statement is used with break. Break exits when the condition matches. This helps to make it easier to understand the code.

Listing 6: Code after refactoring

<html>
<head>
<title>Studying status</title>
</head>
<body>
<?php
$tutorial="java";

switch ($tutorial) {
  case "java":
    echo "Studying Java tutorial!";
    break;
  case "php":
    echo "Studying php tutorial!";
    break;
  case "ruby":
    echo "Studying Ruby tutorial!";
    break;
  default:
    echo "Studying Maths!";
}
?>
</body>
</html>


Figure 9: Output shown above as “Studying Java tutorial”

Conclusion

Refactoring is an important part of coding and should be done by every programmer. It improves the code and its understanding for every user. Easy and fast execution is what you can expect from a PHP program after refactoring. This also brings the code to a format that follows global standards and makes it understandable to programmers all over the world.

About the Author

Kaushik Pal is a technical architect with 15 years of experience in enterprise application and product development. He has expertise in web technologies, architecture/design, java/j2ee, Open source and big data technologies. You can find more of his work at www.techalpine.com and you can email him here.