可以用任何其他更优化的 JAVA 代码替换具有 AND OR NOT 检查的多个 if 条件

发布于 2024-12-05 05:44:58 字数 177 浏览 1 评论 0原文

在我的代码中,有许多没有 else 条件的 If(s)(实际上不需要 else),但我认为是否应该有任何其他代码比多个 if(s) 效率更高。仅供参考,我的 if 就像 if(Some And Or NOTs) if(conditions AND OR NOTS) ...?

请帮助优化代码,因为它已经增加到如此巨大的体积?

In my code there are number of If(s) without else conditions (really else not required) but I think should there be any other code which has much efficiency than multiple if(s). FYI my if are like if(Some And Or NOTs) if(conditions AND OR NOTS) ...?

Please help to optimize the code as it has increased to much huge volume?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

我最亲爱的 2024-12-12 05:44:58

用多态性替换条件式
- <重构、改进现有代码的设计> ,马丁·福勒撰写

replace Conditional with Polymorphism
- < refactoring , improving the design of existing code> ,write by martin fowler

哎呦我呸! 2024-12-12 05:44:58

我不确定您是否已经尝试过这个,但是您可以将 if 语句分组为有意义的函数吗?可以防止代码重复,有时对于小东西,它比多态性更好。

例如,如果您有:

Girl shirly;
Girl ruth;
if(shirly.pretty && shirly.smart && (!shirly.married)){
   ...
}
if(ruth.pretty && ruth.smart && (!ruth.married)){
   ...
}

//a better way will be
if(doILove(shirly)){
...
}
if(doILove(ruth)){
...
}
//or in case of a more general statment
if(doLoveCondition(shirly.pretty,shirly.smart,!shirly.married){
...
}
if(doLoveCondition(ruth.pretty,ruth.smart,!ruth.married){
...
}

如果您发布了代码,那么找到特定的解决方案会更容易。

I am not sure if you tried this already, but can you group your if statements into meaningful functions?could prevent code duplication, and sometimes for small stuff it's better then Polymorphism.

for example if you have:

Girl shirly;
Girl ruth;
if(shirly.pretty && shirly.smart && (!shirly.married)){
   ...
}
if(ruth.pretty && ruth.smart && (!ruth.married)){
   ...
}

//a better way will be
if(doILove(shirly)){
...
}
if(doILove(ruth)){
...
}
//or in case of a more general statment
if(doLoveCondition(shirly.pretty,shirly.smart,!shirly.married){
...
}
if(doLoveCondition(ruth.pretty,ruth.smart,!ruth.married){
...
}

if you would have posted the code, it would have been easier to find a specific solution.

悲喜皆因你 2024-12-12 05:44:58

您可能想查看 switch 语句。

You might want to look into the switch statement.

不即不离 2024-12-12 05:44:58

在我看来,分析应用程序是决定代码是否需要优化的最佳答案。它总是有两种答案:过多的优化甚至可能会导致性能损失,保持简单可以使代码更具可读性,甚至可以根据代码行进行优化。

Profiling application is in my opinion the best answer to decide whether the code needs to optimized. It always has a two way answer too much optimizing even may cause performance loss and keep it simple make the code much readable and even optimized according to line of codes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文