mpdc
mpdc

Reputation: 3570

Getting around duplicating code in complex if/else statements

I come across this problem all the time: you have a series of if/else statements, where the intended result can come from two completely different branches, and you end up duplicating the code across both. Here's an example:

if (condition1) {
    return error
} else {
    if (condition2) {
        return intendedResult
    } else {
        if (condition3) {
            return error
        } else {
            return intendedResult
        }
    }
}

I have this problem in a PHP script at the moment, where the intended result is approximately 200 lines of PHP queries, HTML and additional if/else statements. Is this the prime example of when you should use a function? And return all that code in a concatenated string?

EDIT:

Thanks for all your replies. I can see that my logic would need tidying up. If I gave you a real-world example, could you help me restructure my logic? I think it's a little more complicated than my pseudo-code.

I pull two dates, $lift_deadline and $show_guide_close from a database, and depending on today's date's relation to those, do the following:

if ($lift_deadline > $today) {
    echo "No access until " . $lift_deadline;
} else {
    if ($lift_deadline !== "0000-00-00") {
        if ($today > $show_guide_close) {
            $use_date = $show_guide_close;
        } else {
            $use_date = $lift_deadline;
        }
        echo "HTML Table"; // Intended result goes here, using $use_date
    } else {
        if ($show_guide_close > $today) {
            echo "No access until " . $show_guide_close;
        } else {
            $use_date = $show_guide_close;
            echo "HTML Table"; // Intended result also goes here
        }
    }
}

Upvotes: 0

Views: 43

Answers (3)

Steve
Steve

Reputation: 20469

Well part of the solution is certainly making intendedResult code into a separate method, but just reoganizing the conditions can help:

if ($condition1) {
    return 'error';
}
if (!$condition2 && $condition3) {
    return 'error';
}
return $this->intendedResult();

This could be further simplified to:

return ($condition1 || $condition3) ? 'error' : $this->intendedResult();

But that might not be as readable, and doesnt really illustrate my point, which is as Tom mentions, to flatten your control structure

Upvotes: 2

CT14.IT
CT14.IT

Reputation: 1747

In simple instances I use a switch statement for stuff like this

switch(true)
{
    case (condition1):

        break;
    case (condition2):

        break;
    default:

}

Upvotes: 1

phpPhil
phpPhil

Reputation: 926

Yes, functions are one way to simplify code and make it easier to read. It might be also worth looking into classes and exceptions.

Upvotes: 1

Related Questions