Are you a PHP developer striving for success in your projects?
Writing maintainable code is essential for the success of your project, yet it’s easy to fall into bad habits that can turn your code into a debugging nightmare.
Here’s how you can optimize your coding process and make your life easier.
1. Replace hardcoded values with Constants
When working with values that are used repeatedly throughout your code, it’s best to use constants instead of hardcoding them.
When we hardcode a value, we directly insert the value into the area of code that needs it. This is fine when you hardcode a value once, but as your application grows, more hardcoding means more work.
Rather than hardcoding the same value throughout an application, we can save a reference to the hardcoded value once using a constant.
A constant is the same as a variable, except the value of a constant is immutable, and cannot change. Whereas if you were to change the value of a variable, you can.
You can either define a constant at the top of the relevant class or have a file that stores all of your constants.
Here’s an example of how you can define and use constants in PHP:
private const EVENT_NAME = 'Birthday';
public function getEventName(): string
{
Return self::EVENT_NAME;
}
How to define a constant in PHP:
- Use the keyword const before defining the constant name.
- Define the constant name in capitals.
Benefits of using Constants over hardcoded values:
1. Easier to maintain your application
Changing the value of a constant is easy, you just change the one place where the constant is defined.
But changing a hard-coded value that is referenced all over your application is time-consuming, and you are likely to miss references.
2. Constants make your code more readable
The name of a constant can provide context to the hard-coded value.
This is especially useful for integers, where a number may provide zero context to the reader.
For example:
$totalCost = 100 * 10;
The example above means nothing to a developer with no context. It is impossible to tell what $totalCost means.
But if you assign meaningful names to your hardcoded values through constants, you can provide additional context:
$totalCost = self::HOURLY_RATE * self::HOURS_WORKED;
From the example above we can tell that the value of 100 is the hourly rate and the value of 10 is the number of hours worked.
Use strict equality comparisons over loose equality comparisons
When comparing values in PHP, it’s best to use strict equality comparisons over loose equality comparisons. Strict equality comparisons check if the values being compared are of the same type and have the same value. Loose equality comparisons, on the other hand, only check if the values have the same value, not necessarily the same type.
You should always use strict equality comparisons over loose equality comparisons.
Avoiding this is asking for trouble.
Strict comparison compares the value and data type
public function strictComparison(): bool
{
$value1 = 1;
$value2 = "1";
return $value1 === $value2;
}
Involves using three equals signs to check the value and the data type are the same.
In the example above, the function strictComparison, returns a false, although both $value1 and $value2 have the same value, they do not have the same data type.
Loose comparison compares the value only
public function looseComparison(): bool
{
$value1 = 1;
$value2 = "1";
return $value1 == $value2;
}
A loose comparison uses two equal signs to check for the value of the two items only.
In the example above, the function looseComparison returns a true as they both contain the same value and a loose comparison does not care about the data type.
Benefits of strict comparisons:
- Catch errors early: Strict comparisons will show you an error straight away when there is a mismatch.
- Ensure predictable behavior: You can be sure that only the correct data type gets accepted in a strict comparison.
Drawbacks of strict comparisons:
- Reduced performance: Strict comparisons are less efficient as more checks are required to ensure the two values are the same.
- Challenging to debug for beginners: As a beginner, debugging a strict comparison can be challenging as the nuances between strict and loose comparisons are similar.
3. Avoid using else in conditional statements
Conditional if statements are useful for segregating actions based on specific situations.
But as a beginner, we are taught to follow up every if statement with an else statement, for when a certain condition is not met.
But the else statement is often unnecessary:
public function isUserLoggedIn(User $user): string
{
if ($user->isLoggedIn() === true){
$message = 'User is logged in';
}
else {
$message = 'User is not logged in';
}
return $message;
}
In the example above we use a standard if/else statement to see if the user is logged in or not.
Now let’s try without the else statement:
public function isUserLoggedIn(User $user): string
{
if ($user->isLoggedIn() === true){
return 'User is logged in';
}
return 'User is not logged in';
}
The outcome is exactly the same as the if/else statement, but with less code and easier to read.
The only difference is that we add an early return if the condition is met, to ensure the last line of code is not read.
Benefits of minimizing else statements:
- Simplified logic: With fewer else statements, the logic of the code is easier to understand, and fewer lines of code are used.
- Reduced Nesting: Nesting too many else statements can make code harder to follow.
Drawbacks of minimizing else statements:
- Increased risk of errors: Certain conditions may become overlooked, which can lead to unexpected behavior.
- Reduced Flexibility: When using minimized else statements, it can become difficult to add new conditions or change existing ones.
4. Use ternary operators to avoid complex conditionals
Conditional operators can become complex when overused.
In this scenario, ternary operators can offer a concise alternative which will make your code easy to read.
Here’s an example of how to use ternary operators in PHP:
public function isUserLoggedIn(User $user): string
{
return $user->isLoggedIn() ? 'User is logged in' : 'User is not logged in';
}
In the example above we check to see if the user is logged in by calling $user->isLoggedIn:
- If the method isLoggedIn() returns true, the first string is returned ‘User is logged in’.
- Otherwise, the second string is returned ‘User is not logged in’.
A ternary operator is a shortened version of the if/else statement.
Benefits of ternary operators:
- Better readability of simple conditions: Large if statements can be confusing to read and flow unnaturally.
- Concise display of conditionals: Ternary operators can fit onto one line of code.
Drawbacks of ternary operators:
- Limited functionality: Compared to the if/else statement a ternary operator can only perform one action if a condition is met.
- Reduced readability of complex conditions: Ternary operators shine when the code is simple. Whereas if the return value of a conditional statement is complex, the readability of the code suffers.
Use specific exceptions in try/catch statements
Try/catch statements help you handle errors in your code gracefully, and alert your monitoring system that something is going wrong.
But when writing try-catch statements, it’s best to use specific exceptions instead of generic ones.
Here’s an example of how you can use specific exceptions in PHP:
try {
// Code which would throw the specific exception
} catch (InvalidTypeException $e) {
// Handle the specific exception
}
Benefits of specific exceptions:
- More accurate error reporting: By reporting more precise errors, it becomes easier to diagnose what has gone wrong when debugging.
- More durable code: By using specific exceptions, you can handle errors in a specific way related to the error.
Drawbacks of specific exceptions:
- Larger complexity: As exceptions become more specific, more code needs to be added to account for each exception, adding to the complexity of the code.
- Increase in code: As you add more specific exceptions into your code, you will have to add more code to your application, which will slow down developer velocity.
Comments
Post a Comment
If you have any doubts, please let me know