Search code examples
c#coding-stylecontrol-flow

Control Flow via Return vs. If/Else


Which one is better (implicit control flow via return or control flow via if) -- see below. Please explain what you see as advantage/disadvantage to either one. I like option A because it's less code.

Flow via Return:

public ActionResult Edit(MyClass class)
{
    if (!class.Editable)
       return null;

    class.Update();
    return View();
}

Flow via If/Else:

public ActionResult Edit(MyClass class)
{
    if (class.Editable)
    {
       class.Update();
       return View();
    }
    else
    {
       return null;
    }
}

Solution

  • There's not much difference in this specific example, but in general I like the first approach because it uses a guard clause to return early. If you start adding nested conditions to the second approach you'll see that your code readability will suffer. Guard clauses can go a long way toward reducing the nesting depth, and really enhance the readability of your code.