Click here to Skip to main content
15,889,200 members
Please Sign up or sign in to vote.
2.60/5 (5 votes)
See more:
f1(), f2(), f3() is a function of type bool, which of the following style is better?
C#
A. if (f1 () && f2 () && f3 ()) do ();
B. if (f1 ())
     if (f2 ())
       if (f3 ())
          do ();

If three function execution time is longer, is B method is better? Or they are just the same effect in different write way?
Posted
Updated 21-Jan-13 6:02am
v3

They should be about the same. I prefer A; it's more polished. Any fool can do B.
 
Share this answer
 
v2
Comments
rizwan muhammed khan gouri 22-Jan-13 8:58am    
Why you give Answare For this time besting type of quertion...........
PIEBALDconsult 22-Jan-13 9:01am    
Ummm... what?
It actually doesn't matter from a run-time point of view. In other words, A and B will run equally fast. For readability purposes, however, I would always prefer A. or better yet

if (f1() && f2() && f3())
    doSomething ();
 
Share this answer
 
I'd prefer A. If (f1 () && f2 () && f3 ()) do (); because it is much more clearer and easier to understand.

You are using && which is a short circuit operator.
If the first condition fails the second won't execute so there will be no difference in execution time in either case.
 
Share this answer
 
v3
You left out a 3rd variant:
C#
bool hasSomethingToDo = f1() && f2() && f3();
if (hasSomethingToDo)
{
   DoSomething();
}

and a 4th variant:
C#
bool hasSomethingToDo = f1()
                     && f2()
                     && f3();
if (hasSomethingToDo)
{
   DoSomething();
}


Usually, your functions are not that short as you show above. So, if the function calls are a bit more text, than I go for the 4th variant.

With one or two function calls, I go for the 1st variant. The second variant is the one I avoid as much as possible.

BTW: Execution time shoud not differ in a relevant manner - it's a question of style (if it's relevant, measure it!).

Cheers
Andi
 
Share this answer
 
Any C/C++ compiler nowadays will treat both the same way and generate either the same code or almost the same code.

A point perhaps more important than performance for this one-liner is maintainability. In most cases, 'A' is the better choice - if the logical tests are truly function names or very short expressions.

But this is a razor-thin advantage. If the tests get more complicated, it might be better to break out into multiple 'if' statements for readability purposes. ... and if you ever need to insert an 'else' clause, then 'B' for at least that part of it is better. Don't repeat boolean tests to avoid 'B' logic.

Also never do

C++
if(x == true) {...}
if(x == false) {...}


or you'll never get near my code base...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900