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.
public ActionResult Edit(MyClass class)
{
if (!class.Editable)
return null;
class.Update();
return View();
}
public ActionResult Edit(MyClass class)
{
if (class.Editable)
{
class.Update();
return View();
}
else
{
return null;
}
}
The if-then statement is the most simple control flow we can write. It tests an expression for truth and executes some code based on it.
There are three basic types of logic, or flow of control, known as: Sequence logic, or sequential flow. Selection logic, or conditional flow. Iteration logic, or repetitive flow.
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.
I personally like the if/else
approach. For one, your if
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With