-2

Which way is better?

-- Option 1-------------

if ( condition1 )
{   
    statement1
}
else  
{ 
    exit program
}

if ( condition2 ) 
{   
    statement2  
}
else 
{  
    exit program 
}

----Option 2------

if ( condition1 )
{

    statement 1

    if ( condition2 ) 
    { 

        statement2   

    }
    else 
    { 
        exit program
    }

}
else
{
    exit program
}
3
  • As per the answers in the duplicate question, neither is good. It is better to move the code inside the if ( condition1 ) block in your second example to another method/function.
    – David Arno
    Commented Aug 19, 2016 at 10:18
  • @TulainsCórdova You need to read the code again. They are equivalent.
    – David Arno
    Commented Aug 20, 2016 at 3:42
  • 1
    @DavidArno You are right. I missread. Commented Aug 20, 2016 at 4:02

3 Answers 3

2

I generally prefer ... (I guess it depends on type of algorithm you are dealing with, density of code, ease of comprehension you are targeting for) ...

if ( ! condition1 ) { exit; }
statement1;

if ( ! condition2 ) { exit; }    
statement2;

Your mileage may vary.

-3

This is quite a subjective question, and it might also depend on what kind of language you are using.
It really depends on what you have put in your statement1 and statement2.

The most important part of any question like this is readability. Does one approach look better? Remove duplicate code? Reduce code bloat?

There is also a matter of scope. If you have a variable such as:

var variable;
if (condition1)
{
    variable = someValue;
}

if (condition2)
{
    function(variable);
}

Then it might be better nested.

if (condition1)
{
    var variable = someValue;
    if (condition2)
    {
        function(variable);
    }
}

Then there is a matter of maintainability.
If the statements are unrelated (they share no local variables and neither conditions or statements depend on the other), then separating them would be more readability and quicker to edit. You won't have to consider the previous condition when imagining the code's workflow.

You might want to consider separating them into functions, if they are completely separate.

1
  • 1
    Your variations don't do the same thing. The first variant calls function with an undefined value if condition1 is false and condition2 is true.
    – gnasher729
    Commented Aug 19, 2016 at 22:51
-5

Use a switch. The switch will allow multiple cases for different conditions.

switch(expression) {
    case n:
        code block
        break;
    case n:
        code block
        break;
    default:
        default code block
}
1
  • 2
    condition 2 is only available after statement 1 has run and finished Commented Aug 19, 2016 at 2:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.