Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To "if, if, if" or to "if, else if, else if, else" [closed]

Tags:

I am writing some code for data analysis, and have to exclude samples based on some criteria. In practice I end up writing code such as:

bool Test(SampleType sample)
{
  if( ! SubTest1(sample) )
    return false;
  if( ! SubTest2(sample) )
    return false;
  if( ! SubTest3(sample) )
    return false;

  return true;
}

The following seems equivalent to me:

bool Test(SampleType sample)
{
  if( ! SubTest1(sample) )
    return false;
  else if( ! SubTest2(sample) )
    return false;
  else if( ! SubTest3(sample) )
    return false;
  else 
    return true;
}

Is there a difference in terms of computing cost? Is there a arguable preferential one in terms of extendibility/maintainability, aesthetics, etc...?

I know this is probably an inconsequential issue, but once I get these questions stuck in my head I NEED to find the answer.

PS: in case anyone cares, my actual code as of 15/09 can be found at the following: http://folk.uio.no/henrikq/conf.tgz

like image 770
qonf Avatar asked Sep 14 '11 10:09

qonf


People also ask

Does if-else need to end with Else?

else can be omitted for any if statement, there is nothing special in the last if of an if / else if chain. This is documented in any JavaScript grammar, e.g. in the specification.

What is if-else if structure?

The if/else if statement allows you to create a chain of if statements. The if statements are evaluated in order until one of the if expressions is true or the end of the if/else if chain is reached. If the end of the if/else if chain is reached without a true expression, no code blocks are executed.

Can you put two conditions in an if statement Java?

Java else if StatementWe can use multiple if and else statements as long as a condition is not met. Note: we can have multiple else if statements but we always terminate with an else statement.

Which is faster if or else?

Speed: A switch statement might prove to be faster than ifs provided number of cases are good. If there are only few cases, it might not effect the speed in any case. Prefer switch if the number of cases are more than 5 otherwise, you may use if-else too.


1 Answers

Compiler generates the same code for both the versions. But the 1st version is better in maintainability aspect if you compare just with the 2nd version.

The code exits when the return statement is encountered; so there is no use of keeping else in the upcoming if. It makes the developer understand the code better.

Also, if this is the literal code then you can still shrink as,

bool Test(SampleType sample)
{
  return (SubTest1(sample) && SubTest2(sample) && SubTest3(sample));
}
like image 75
iammilind Avatar answered Oct 20 '22 07:10

iammilind