问题
Is there a better way to write the code below? I'm checking if an object is null, returning false if it is, otherwise I check another variable and choose what to do based on that.
private boolean myFunction(MyObjectType myObject) {
if (myObject == null) {
return false;
} else if (myInstanceVariable.myMethod()) {
// Do something then return
System.out.println(myObject.getSomeValue());
return true;
} else {
return false;
}
}
Is it better to have the final else statement or move the return false
(and any other code that I may have put before it inside the final else { }
block) outside the if statement? I could see it being safer (and fewer lines of code) to move it outside so the function is 100% guaranteed to return. Could it depend on how the compiler behaves?
private boolean myFunction(MyObjectType myObject) {
if (myObject == null) {
...
} else if (myVariable.myMethod()) {
...
}
return false;
}
回答1:
It's better to have the last return statement in the end outside any if statements. Also last I remember, if all your returns are inside if statements you will get a compilation error stating the method doesn't have a return or that the return may not always be reached.
回答2:
For me, this is better:
private boolean myFunction(MyObjectType myObject) {
if (myObject == null) {
return false;
}
if (myInstanceVariable.myMethod()) {
// Do something then return
System.out.println(myObject.getSomeValue());
return true;
}
return false;
}
If you are returning from inside an if
block, then you don't need an else
block. I find it better because the true complexity of the logic is better expressed by this less-complex looking method. Fewer braces and less indentation makes it easier to understand, at least for me.
来源:https://stackoverflow.com/questions/26003104/java-best-style-for-return-statement-inside-or-outside-if-condition