我一直遇到这个问题:您有一系列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
}
}
}
解决方案的一部分当然是将intendedResult
代码变成一个单独的方法,但是仅重新定义条件可以有所帮助:
if ($condition1) {
return 'error';
}
if (!$condition2 && $condition3) {
return 'error';
}
return $this->intendedResult();
这可以进一步简化为:
return ($condition1 || $condition3) ? 'error' : $this->intendedResult();
但这可能不那么可读,也并不能真正说明我的观点,这就是汤姆提到的使控制结构扁平化的观点。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句