用保护从句替换嵌套条件句
问题
你有一组嵌套的条件,很难确定正常的代码执行流程。
解决方案
将所有特殊检查和边缘情况分离到单独的子句中,并将它们放在主检查之前。理想情况下,你应该有一个“固定的”条件列表,一个接一个。
之前
public double getPayAmount(){双结果;if (isDead){result = deadAmount();} else {if (isSeparated){result = separatedAmount();} else {if (isRetired){result = retiredAmount();} else{result = normalPayAmount();返回结果;}
后
public double getPayAmount() {if (isDead){return deadAmount();} if (isSeparated){返回separatedAmount();} if (isRetired){返回retiredAmount();} return normalPayAmount();}
之前
public double GetPayAmount() {double result;if (isDead){结果= DeadAmount();} else {if (isSeparated) {result = SeparatedAmount();} else {if (isRetired) {result = RetiredAmount();} else {result = NormalPayAmount();返回结果;}
后
public double GetPayAmount() {if (isDead) {return DeadAmount();} if (isSeparated){返回SeparatedAmount();} if (isRetired){返回RetiredAmount();} return NormalPayAmount();}
之前
函数getPayAmount() {if ($this->isDead) {$result = $this->deadAmount();} else {if ($this->isSeparated) {$result = $this->separatedAmount();} else {if ($this->isRetired) {$result = $this->retiredAmount();} else {$result = $this->normalPayAmount();}}}返回$result;}
后
函数getPayAmount() {if ($this->isDead){返回$this->deadAmount();} if ($this->isSeparated){返回$this->separatedAmount();} if ($this->isRetired){返回$this->retiredAmount();}返回$this->normalPayAmount();}
之前
def getPayAmount(self): if self。isDead:结果= deadAmount() else: if self。isSeparated: result = separatedAmount() else: if self。isRetired: result = retiredAmount() else: result = normalPayAmount()返回结果
后
def getPayAmount(self): if self。如果self. isDead:返回deadAmount()。如果self. isSeparated:返回separatedAmount()。isRetired:返回retiredAmount()返回normalPayAmount()
之前
getPayAmount(): number {let result: number;if (isDead){result = deadAmount();} else {if (isSeparated){result = separatedAmount();} else {if (isRetired){result = retiredAmount();} else{result = normalPayAmount();返回结果;}
后
getPayAmount(): number {if (isDead){return deadAmount();} if (isSeparated){返回separatedAmount();} if (isRetired){返回retiredAmount();} return normalPayAmount();}
为什么重构
发现“来自地狱的条件句”相当容易。每一层窝的凹痕形成一个箭头,指向痛苦和悲伤的方向:
If () {If () {do {If () {If () {If () {If(){…}}…}……} while ();...}其他{…}}
很难弄清楚每个条件是做什么的,以及如何做的,因为代码执行的“正常”流程并不是立即明显的。这些条件表明了混乱的进化,每个条件的添加都是权宜之计,而没有考虑优化整体结构。
为了简化这种情况,将特殊情况隔离为单独的条件,这些条件立即结束执行,如果保护子句为真,则返回空值。实际上,您在这里的任务是使结构平坦。
如何重构
试着去除代码的副作用将查询和修饰符分开可能会有帮助。这个解决方案对于下面描述的重新洗牌是必要的。
隔离所有导致调用异常或立即从方法返回值的保护子句。将这些条件放在方法的开头。
重新排列完成并且所有测试都成功完成后,查看是否可以使用巩固条件表达式用于导致相同异常或返回值的监护子句。