Skip to content
PHP Reusability Conditional Statments Code Readibility Code Quality

Don't Cram Logic Into if-Give It a Name

Muhammad Raheel

Muhammad Raheel

May 2nd, 2025 · 2 min read

Don't Cram Logic Into if-Give It a Name

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.

Found this useful?

Support the work that goes into these posts.

Support
Comments


Comment created and will be displayed once approved.