问题
Here is some hypothetical code sample:
if (e.KeyCode == Keys.Enter)
{
if (this.CurrentElement == null) {
return false;}
if (this.CurrentElement == this.MasterElement) {
return false;}
if (!Validator.Exist (this.CurrentElement)) {
return false;}
if (!Identifier.IsPictureElement (this.CurrentElement)) {
return false;}
this.FlattenObjects(this.CurrentElement);
}
VS
if (e.KeyCode == Keys.Enter)
{
if (this.CurrentElement != null) {
if (this.CurrentElement != this.MasterElement) {
if (Validator.Exist (this.CurrentElement)) {
if (Identifier.IsPictureElement (this.CurrentElement)) {
this.FlattenObjects(this.CurrentElement);}}}}}}
}
Which one do you think is better in terms of readability, maintenance, etc?
Also the 2nd example can be formatted differently via the different use of parenthesis.
回答1:
Early returns are much more readable.
Whenever you get more than four or five levels of nesting inside a method, it's time to refactor that method.
A single if with an || clause can sometimes be more readable:
if (this.CurrentElement == null
|| this.CurrentElement == this.MasterElement
|| !Validator.Exist(this.CurrentElement)
|| !Identifier.IsPictureElement(this.CurrentElement))
return false;
回答2:
The first example is better in every way. It's simpler, and easier to read. Some people say that every function should have a single return point; this example shows clearly why those people are wrong.
PS Personally I would remove all those superfluous curly brackets:
if (this.CurrentElement == null) return false;
etc. This makes it even simpler, and even easier to read.
回答3:
I think I would write it like:
if (this.CurrentElement == null OR this.CurrentElement == this.MasterElement OR ...) return false;
回答4:
I'd say the first is better for readability and maintenance. However, I'd probably write it something like this.
if (e.KeyCode == Keys.Enter) {
if(this.CurrentElement == null ||
this.CurrentElement == this.MasterElement ||
!validator.exists(this.CurrentElement) ||
!identifier.isPictureElement(this.CurrentElement))
{
return false;
{
else
{
this.flattenObjects(this.CurrentElement);
}
}
回答5:
Given that in the second example "false" is the return for all paths but it is implicit rather than declared why not just make all returns implicitly false and simply test for the one condition that is unique?
This might violate someone's style guidelines but logically is the most succinct.
if( e.KeyCode == Keys.Enter
&& this.CurrentElement != null
&& this.CurrentElement != this.MasterElement
&& Validator.Exist (this.CurrentElement)
&& Identifier.IsPictureElement (this.CurrentElement))
this.FlattenObjects(this.CurrentElement);
来源:https://stackoverflow.com/questions/4369822/early-returns-vs-nested-positive-if-statements