Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Control Flow via Return vs. If/Else [closed]

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;
    }
}
like image 861
Alex Avatar asked Sep 14 '09 01:09

Alex


People also ask

Are IF statements control flow?

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.

What are the types of control flow?

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.


2 Answers

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.

like image 158
Bill the Lizard Avatar answered Sep 21 '22 09:09

Bill the Lizard


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.

like image 28
Eric Avatar answered Sep 20 '22 09:09

Eric