在复杂的if / else语句中绕过复制代码

时间:2015-02-27 15:18:53

标签: php

我一直遇到这个问题:你有一系列if/else语句,其中预期的结果可能来自两个完全不同的分支,你最终会在两者之间复制代码。这是一个例子:

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

我目前在PHP脚本中遇到此问题,其中预期结果是大约200行PHP查询,HTML和其他if/else语句。这是你应该使用函数的主要例子吗?并return串联字符串中的所有代码?

修改

感谢您的所有回复。我可以看到我的逻辑需要整理。如果我给你一个真实世界的例子,你能帮助我重构我的逻辑吗?我认为它比我的伪代码复杂一点。

我从数据库中提取了两个日期$lift_deadline$show_guide_close,并根据今天的日期与这些日期的关系,执行以下操作:

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
        }
    }
}

3 个答案:

答案 0 :(得分:2)

解决方案的一部分肯定是将intendedResult代码转换为单独的方法,但只需重新编写条件就可以提供帮助:

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

这可以进一步简化为:

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

但这可能不那么可读,并没有真正说明我的观点,正如汤姆所提到的那样,要平整你的控制结构

答案 1 :(得分:1)

是的,函数是简化代码并使其更易于阅读的一种方法。也许值得研究classesexceptions

答案 2 :(得分:1)

在简单的例子中,我为这样的东西使用了switch语句

switch(true)
{
    case (condition1):

        break;
    case (condition2):

        break;
    default:

}