Code optimization is essential for maintaining efficient and manageable software projects. This article explores practical techniques for improving the readability and maintainability of PHP code, presenting concrete "before" and "after" examples for each technique discussed.
Using Formatting Tools
To ensure consistency in formatting, tools like .editorconfig
are essential.
Example:
Before:
function calculate($x,$y) { return $x+$y; }
After:
function calculate($x, $y) {
return $x + $y;
}
Code Comment and Removal of Unused Items
In addition to removing commented code, it is essential to eliminate unused variables and functions, which clarifies the purpose of the active code.
Example:
Before:
// Calculate the total
function calculateTotal($items) {
$x; // Old unused variable
return array_sum(array_column($items, 'price'));
}
After:
function calculateTotal($items) {
return array_sum(array_column($items, 'price'));
}
Implementation of "Early Return"
Reduces complexity by avoiding excessive nesting, using early returns.
Example:
Before:
function isEligible($age) {
if ($age > 18) {
return true;
} else {
return false;
}
}
After:
function isEligible($age) {
return $age > 18;
}
Use of the Ternary Operator
The ternary operator allows you to write conditions more concisely and clearly, reducing the number of lines of code.
Example:
Before:
function getStatus($user) {
if ($user->isActive()) {
return 'Active';
} else {
return 'Inactive';
}
}
After:
function getStatus($user) {
return $user->isActive() ? 'Active' : 'Inactive';
}
Reducing the Use of "else"
Eliminating "else" after "if" simplifies the logic.
Example:
Before:
if ($condition) {
performAction();
} else {
handleAlternative();
}
After:
if ($condition) {
performAction();
return;
}
handleAlternative();
Simplifying Nested Conditions
Simplify nested conditions into a single expression.
Example:
Before:
if ($user->isActive) {
if ($user->age >= 18) {
approveUser($user);
}
}
After:
if ($user->isActive && $user->age >= 18) {
approveUser($user);
}
Efficient Use of Model Data
Load only the necessary data from a model.
Example:
Before:
$dataIni = Yii::$app->request->post('Banner')['dataIni'];
$dataFim = Yii::$app->request->post('Banner')['dataFim'];
After:
$bannerPost = Yii::$app->request->post('Banner');
$dataIni = $bannerPost['dataIni'];
$dataEnd = $bannerPost['dataEnd'];
Replacing Depreciated Items
Update class or method references to avoid obsolescence.
Example:
Before:
$class = AccessControl::className();
After:
$class = AccessControl::class;
Avoid Magic Numbers
Replace arbitrary numbers with named constants.
Example:
Before:
if ($user->age >= 18) {
approveUser($user);
}
After:
const MIN_AGE_FOR_APPROVAL = 18;
if ($user->age >= MIN_AGE_FOR_APPROVAL) {
approveUser($user);
}
Preference for "foreach" over "for"
Use simpler and clearer iteration structures.
Example:
Before:
for ($i = 0; $i < count($users); $i++) {
echo $users[$i]->name;
}
After:
foreach ($users as $user) {
echo $user->name;
}
Modularization of Functions
Break large functions into smaller functions to make it easier to understand.
Correct Use of Private Functions
Set internal-use functions to private to protect and organize code.
Use Pass-by-Reference Where Appropriate
Encourage the use of pass by reference in situations where large objects or collections of data are manipulated frequently. This can significantly reduce memory overhead and increase application performance.
Example:
Before:
function modifyItem($array, $index, $newValue) {
$array[$index] = $newValue; // Modification is local
return $array; // Need to return the modified array
}
$myArray = [1, 2, 3];
$myArray = modifyItem($myArray, 1, 20); // Reassignment required
print_r($myArray);
š” NOTE: In this case, the modifyItem function needs to return the modified array, and then the original array must be reassigned with this new returned value, which implies more intensive memory management.
After:
function modifyItem(&$array, $index, $newValue) {
$array[$index] = $newValue; // The modification affects the original array directly
}
$myArray = [1, 2, 3];
modifyItem($myArray, 1, 20); // No reassignment required
print_r($myArray);
š” NOTE: Here, the modifyItem function uses the & symbol in the $array parameter to indicate that the array is passed by reference. This means that any modification to the array within the function will directly affect the original array without the need to return and reassign it. The modification is done directly in the memory where the original array is stored, saving resources and simplifying the code.
Using the Null Coalesce Operator in PHP
The null coalesce operator (??) is a useful addition to PHP that helps you write cleaner, more efficient code when dealing with values āāthat can be null. This operator is especially useful for simplifying the assignment of default values āāto variables that may not be defined or that may contain a null value.
Example:
Before:
$username = isset($_GET['username']) ? $_GET['username'] : 'guest';
After:
$username = $_GET['username'] ?? 'guest';
Conclusion
By implementing these practices, developers ensure that code is clean, efficient, and easy to understand, making both maintenance and collaboration on software projects easier.
Thanks for reading!
If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!
šš See you later! šš
Support Me
Youtube - WalterNascimentoBarroso
Github - WalterNascimentoBarroso
Codepen - WalterNascimentoBarroso
Top comments (2)
Thank you very much!!!
I have the Magic Numbers situation, I didn't know how to improve it!
You're welcome