Code Improvements
Tags: tutorial, webdev, php, beginners
Published: 2024-05-08 22:30:19

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:**
```php
function calculate($x,$y) { return $x+$y; }
```

**After:**
```php
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:**

```php
// Calculate the total 
function calculateTotal($items) {
 $x; // Old unused variable
 return array_sum(array_column($items, 'price'));
}
```
**After:**

```php
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:**

```php
function isEligible($age) {
 if ($age > 18) {
 return true;
 } else {
 return false;
 }
}
```

**After:**

```php
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:**

```php
function getStatus($user) {
 if ($user->isActive()) {
  return 'Active';
 } else {
  return 'Inactive';
 }
}
```

**After:**

```php
function getStatus($user) {
 return $user->isActive() ? 'Active' : 'Inactive';
}
```

## Reducing the Use of "else"
Eliminating "else" after "if" simplifies the logic.

**Example:**
**Before:**

```php
if ($condition) {
 performAction();
} else {
 handleAlternative();
}
```

**After:**

```php
if ($condition) {
 performAction();
 return;
}
handleAlternative();
```

## Simplifying Nested Conditions
Simplify nested conditions into a single expression.

**Example:**
**Before:**

```php
if ($user->isActive) {
 if ($user->age >= 18) {
 approveUser($user);
 }
}
```

**After:**

```php
if ($user->isActive && $user->age >= 18) {
 approveUser($user);
}
```

## Efficient Use of Model Data
Load only the necessary data from a model.

**Example:**
**Before:**

```php
$dataIni = Yii::$app->request->post('Banner')['dataIni'];
$dataFim = Yii::$app->request->post('Banner')['dataFim'];
```

**After:**

```php
$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:**

```php
$class = AccessControl::className();
```

**After:**

```php
$class = AccessControl::class;
```

## Avoid Magic Numbers
Replace arbitrary numbers with named constants.

**Example:**
**Before:**

```php
if ($user->age >= 18) {
 approveUser($user);
}
```

**After:**

```php
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:**

```php
for ($i = 0; $i < count($users); $i++) {
 echo $users[$i]->name;
}
```

**After:**

```php
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:**

```php
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:**

```php
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:**

```php
$username = isset($_GET['username']) ? $_GET['username'] : 'guest';
```

**After:**

```php
$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](https://www.youtube.com/channel/UCXm0xRtDRrdnvkW24WmkBqA)
[Github - WalterNascimentoBarroso](https://github.com/walternascimentobarroso)
[Codepen - WalterNascimentoBarroso](https://codepen.io)