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;
}
}
I prefer
if/else
, too. Legibility, readability and maintainability stands above anything else, for me.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.
Both of those statements are controlling flow via an
if
statement. It's just a matter of how you handle the condition.I'm always on the fence when it comes to writing logic statements like this. Part of me likes the first option because it's a little less code. The other part of me likes the second option because it's much easier to follow the flow of logic. With the first option, it's easy to miss the return statement which can lead to manageability issues in the future.
...and for that reason, the second option always wins in my book. It's better to write code that is easier to read and maintain than try to take shortcuts.
Exit early - I prefer to see all the conditions that will cause the method to exit without doing much up front. I avoid else statements if I can at all avoid it.
This is actually a fairly prominent school of thought among the Code Contracts crowd.
First option, using return, is better, because:
One proponent of this method (return) is Marcus Zarra, in the Cocoa is my Girlfriend coding style
I personally like the
if/else
approach. For one, yourif
statement is a positive, not a negative, making it easier to read. For two, you've encapsulated the conditions in curly brackets, and I'm a fan of that style.Anyway, it's much easier to follow what's going on in the second than in the first. And that always wins in my book.