-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 Answers3

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.

blackpen
  • 191
  • 5
-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.

Erdrik Ironrose
  • 4,806
  • 3
  • 13
  • 25
  • 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 Aug 19 '16 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
}
user241585
  • 11
  • 2