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
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.
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.
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.
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.
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));
}
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