Code Smell | Complex Conditions

Code Smell | Complex Conditions

July 13, 2024

codequality
refactorit
code-smell
complex-conditions

Complex conditions in if statements can make your code difficult to read, understand, and maintain. These conditions often involve multiple logical operators and nested expressions, which can quickly become overwhelming. Instead of writing intricate if statements, it's better to use variables or functions that clearly describe the condition, and even split these conditions into multiple variables or functions if necessary.

Identifying Complex Conditions

Let's start with an example of a complex if condition:

function isEligibleForDiscount(user: User): boolean {
    return (
        user.age > 18 &&
        user.age < 65 &&
        user.isMember &&
        user.lastPurchaseDate >
            new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) &&
        user.purchaseHistory.length > 5
    )
}

In this example, the if statement is evaluating multiple conditions at once, making it hard to read and understand at a glance.

Improving Readability with Variables

We can improve readability by breaking down the complex condition into descriptive variables:

function isEligibleForDiscount(user: User): boolean {
    const isAdult = user.age > 18 && user.age < 65
    const isRecentBuyer =
        user.lastPurchaseDate > new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
    const hasFrequentPurchases = user.purchaseHistory.length > 5
 
    return isAdult && user.isMember && isRecentBuyer && hasFrequentPurchases
}

Now, the condition is more readable as each part of the condition is represented by a well-named variable.

Enhancing Maintainability with Functions

For even better maintainability and reuse, you can extract the conditions into separate functions:

function isAdult(user: User): boolean {
    return user.age > 18 && user.age < 65
}
 
function isRecentBuyer(user: User): boolean {
    return (
        user.lastPurchaseDate > new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
    )
}
 
function hasFrequentPurchases(user: User): boolean {
    return user.purchaseHistory.length > 5
}
 
function isEligibleForDiscount(user: User): boolean {
    return (
        isAdult(user) &&
        user.isMember &&
        isRecentBuyer(user) &&
        hasFrequentPurchases(user)
    )
}

This approach makes the code more modular and each function has a single responsibility, making it easier to test and maintain.

Conclusion

By avoiding complex if conditions and using descriptive variables or functions, you can make your code more readable and maintainable. This not only helps you but also others who might work on the code in the future. Always strive for clarity in your code to prevent misunderstandings and reduce the likelihood of errors.

Remember, clean code is not just about making the code work, but making it understandable for humans as well.


Thanks for reading me 😊