本文介绍了具有多个条件的一个 if 语句的良好架构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
限时送ChatGPT账号..我有一个看起来像这样的 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
返回方法,并在 if
块中调用这些方法.
Group the similar conditions by their functionality and name that functionality.
Create Boolean
returning methods for each group and call those in the if
block.
这篇关于具有多个条件的一个 if 语句的良好架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论