我总是尽量避免嵌套语句。
他们引导我将代码放入长长的花括号中。 当每个条件中的代码量变大时,变得很难遵循代码。
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.
更多推荐
发布评论