良好的架构为一个if语句有很多条件 [英] Good architecture for one if statement with many conditions
本文介绍了良好的架构为一个if语句有很多条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个if语句,如下所示:
I have an if statement which looks like this:
if conditionA() || conditionB() || conditionC() || conditionD() || conditionE() || condition()
#do sth
end
#conditionX() methods return true/false
这看起来很丑陋。有没有任何设计模式可以简化?
This looks ugly. Is there any design pattern which would simplify this?
*使用的语言:Ruby。虽然我认为一个解决方案应该是语言无关的
*Language used: Ruby. Although I think a solution should be language-agnostic
推荐答案
如果超出可维护性的条件太多,最好的事情是抽象的。
If there are too many conditions beyond maintainability, the best thing you can do is abstraction.
- 通过功能组合类似的条件,并命名该功能。
- 创建
Boolean
返回每个组的方法,并调用中的那些,如果
块。
- Group the similar conditions by their functionality and name that functionality.
- Create
Boolean
returning methods for each group and call those in theif
block.
这篇关于良好的架构为一个if语句有很多条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文