如何使用带功能的if

编程入门 行业动态 更新时间:2024-10-22 10:56:15
如何使用带功能的if-else语句返回?(How to use if-else statement with function returns? [closed])

我总是尽量避免嵌套语句。

他们引导我将代码放入长长的花括号中。 当每个条件中的代码量变大时,变得很难遵循代码。

if(condtion) { } else if(condition2) { } else { }

所以如果我有这样的代码:

void doSomething(){ if(condtion) { return; } else if(condition2) { return; } else { return; } }

我总是将它改为这种形式(由于每个条件都有一个return语句,所以我避免了else情况):

void doSomething() { if(condtion) { return; } if(condition2) { return; } return; }

但有人告诉我,我的阅读有点困难,哪一个更好?

I always try to avoid nested statements.

They lead me into putting code into a long curly braces. It becomes hard to follow the code when the amount of code with in each condition becomes larger.

if(condtion) { } else if(condition2) { } else { }

So if I have code like this:

void doSomething(){ if(condtion) { return; } else if(condition2) { return; } else { return; } }

I always change it to this form (I avoided the else as there is a return statement from each condition):

void doSomething() { if(condtion) { return; } if(condition2) { return; } return; }

But someone told me mine is a bit hard to read, which one is better?

最满意答案

如果条件是一些快速情况或先决条件,我宁愿立即return或throw没有else语句。 例如:

void processArray(int[] array) { if(array == null || array.length == 0) { System.out.println("Empty input"); return; } // do some complex computations }

这样,你的方法的其余部分是主程序没有额外的缩进和没有额外的大括号,可能低于else语句。

如果条件分支很长并且长度大致相同,那么代码就会有异味。 你需要重构它提取分支到方法或(有时更好)分离类使用类似命令模式 。

If conditions are some quick-cases or preconditions, I prefer immediate return or throw without an else statement. For example:

void processArray(int[] array) { if(array == null || array.length == 0) { System.out.println("Empty input"); return; } // do some complex computations }

This way the rest of your method which is the main course has no extra indent and no extra brace at the end which probably way below the else statement.

If conditional branches are quite long and has roughly the same length, then the code smells anyways. You need to refactor it extracting the branches to methods or (sometimes better) to separate classes using something like Command pattern.

更多推荐

本文发布于:2023-07-26 00:17:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1268350.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   功能

发布评论

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

>www.elefans.com

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