As a developer, I have often encountered if statements that are overloaded with multiple conditions. While they work functionally, they can be challenging to read and maintain. Let's consider an example:
if(
$admission->admitcard &&
in_array($admission->code,$admissionCodes) &&
$admission->status == AdmissionStatus::APPROVED
){
// other code
}
At first glance, these conditions might make sense. However, as the logic grows, it becomes harder to understand the intention behind the conditions.
Name Your Conditions
To better enhance readability and maintainability, it’s better to extract complex conditions into well-named variables. Let’s refactor the condition using a name.
$eligibleAdmission = $admission->admitcard &&
in_array($admission->code,$admissionCodes) &&
$admission->status == AdmissionStatus::APPROVED;
if($eligibleAdmission){
// other code
}
Benefits of This Approach
- Improved Readability: By naming complex conditions, the code becomes self-explanatory — you don’t even need comments.
- Reusability: Once assigned to a variable, the variable can be reused without a mess.
- Enhanced Maintainability: Changes to the condition need to be made in only one place.
Conclusion
Writing all logic directly in an if statement might feel quick, but taking a moment to name it pays off. It's a small tweak that leads to clearer, cleaner, and more maintainable code.
Hope this little trick helps you write better code. If you think this post is helpful, you can follow my profile to get more tricks and tips.
Top comments (0)