DEV Community

Walter Nascimento
Walter Nascimento

Posted on

Code Improvements

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; }
Enter fullscreen mode Exit fullscreen mode

After:

function calculate($x, $y) {
 return $x + $y;
}
Enter fullscreen mode Exit fullscreen mode

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'));
}
Enter fullscreen mode Exit fullscreen mode

After:

function calculateTotal($items) {
 return array_sum(array_column($items, 'price'));
}
Enter fullscreen mode Exit fullscreen mode

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;
 }
}
Enter fullscreen mode Exit fullscreen mode

After:

function isEligible($age) {
 return $age > 18;
}
Enter fullscreen mode Exit fullscreen mode

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';
 }
}
Enter fullscreen mode Exit fullscreen mode

After:

function getStatus($user) {
 return $user->isActive() ? 'Active' : 'Inactive';
}
Enter fullscreen mode Exit fullscreen mode

Reducing the Use of "else"

Eliminating "else" after "if" simplifies the logic.

Example:
Before:

if ($condition) {
 performAction();
} else {
 handleAlternative();
}
Enter fullscreen mode Exit fullscreen mode

After:

if ($condition) {
 performAction();
 return;
}
handleAlternative();
Enter fullscreen mode Exit fullscreen mode

Simplifying Nested Conditions

Simplify nested conditions into a single expression.

Example:
Before:

if ($user->isActive) {
 if ($user->age >= 18) {
 approveUser($user);
 }
}
Enter fullscreen mode Exit fullscreen mode

After:

if ($user->isActive && $user->age >= 18) {
 approveUser($user);
}
Enter fullscreen mode Exit fullscreen mode

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'];
Enter fullscreen mode Exit fullscreen mode

After:

$bannerPost = Yii::$app->request->post('Banner');
$dataIni = $bannerPost['dataIni'];
$dataEnd = $bannerPost['dataEnd'];
Enter fullscreen mode Exit fullscreen mode

Replacing Depreciated Items

Update class or method references to avoid obsolescence.

Example:
Before:

$class = AccessControl::className();
Enter fullscreen mode Exit fullscreen mode

After:

$class = AccessControl::class;
Enter fullscreen mode Exit fullscreen mode

Avoid Magic Numbers

Replace arbitrary numbers with named constants.

Example:
Before:

if ($user->age >= 18) {
 approveUser($user);
}
Enter fullscreen mode Exit fullscreen mode

After:

const MIN_AGE_FOR_APPROVAL = 18;
if ($user->age >= MIN_AGE_FOR_APPROVAL) {
 approveUser($user);
}
Enter fullscreen mode Exit fullscreen mode

Preference for "foreach" over "for"

Use simpler and clearer iteration structures.

Example:
Before:

for ($i = 0; $i < count($users); $i++) {
 echo $users[$i]->name;
}
Enter fullscreen mode Exit fullscreen mode

After:

foreach ($users as $user) {
 echo $user->name;
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

💡 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);
Enter fullscreen mode Exit fullscreen mode

💡 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';
Enter fullscreen mode Exit fullscreen mode

After:

$username = $_GET['username'] ?? 'guest';
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
cbrghton profile image
Brighton Saldaña

Thank you very much!!!
I have the Magic Numbers situation, I didn't know how to improve it!

Collapse
 
walternascimentobarroso profile image
Walter Nascimento

You're welcome