Search code examples
coding-style

Early returns vs nested positive if statements


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.


Solution

  • 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;