I have a couple of methods that return a bool depending on their success, is there anything wrong with calling those methods inside of the IF() ?
//&& makes sure that Method2() will only get called if Method1() returned true, use & to call both methods
if(Method1() && Method2())
{
// do stuff if both methods returned TRUE
}
Method2() doesn't need to fire if Method1() returns FALSE.
Let me know there's any problem with the code above.
thank you.
EDIT: since there was nothing wrong with the code, I'll accept the most informative answer ... added the comment to solve the "newbie & &&" issue
I'll throw in that you can use the & operator
(as opposed to &&
) to guarantee that both methods are called even if the left-hand side is false
, if for some reason in the future you wish to avoid short-circuiting.
The inverse works for the | operator
, where even if the left-hand condition evaluates to true
, the right-hand condition will be evaluated as well.
No, there is nothing wrong with method calls in the if condition. Actually, that can be a great way to make your code more readable!
For instance, it's a lot cleaner to write:
private bool AllActive()
{
return x.IsActive && y.IsActive && z.IsActive;
}
if(AllActive())
{
//do stuff
}
than:
if(x.IsActive && y.IsActive && z.IsActive)
{
//do stuff
}
As useful as they are, sequence points can be confusing. Unless you really understand that, it is not clear that Method2() might not get called at all. If on the other hand you needed BOTH methods to be called AND they had to return true, what would you write? You could go with
bool result1 = Method1();
bool result2 = Method2();
if (result1 && result2)
{
}
or you could go with
if (Method1())
if (Method2())
{
}
So I guess the answer to you question IMHO is, no, it's not exactly clear what you mean even though the behavior will be what you describe.
I would only recommend it if the methods are pure (side-effect-free) functions.
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