具有多个条件的一个 if 语句的良好架构

编程入门 行业动态 更新时间:2024-10-27 22:19:27
本文介绍了具有多个条件的一个 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:关键词]

本文发布于:2023-04-17 01:34:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/901434.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   语句   架构   条件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!