Let's say for example that you have a code that checks if a "boolean" flag is true to run some procedure, like this:
if( my_flag ){
doStuff();
}
I could write it using a short-circuit evaluation, this is taking in account that the result from the evaluation has no value to the rest of the code, it could be written like:
my_flag && doStuff();
I have seen professional code written like this, from my perspective it improves readability removing innecesary syntax, but I have no idea if this is a good practice or not because I have also seen a lot of code written using the if
statement.
I would like to know if theres something that I'm not taking in account or arguments against its use in trivial cases.
CodePudding user response:
Is shortcircuit evaluation a good practice to replace if statements that seem trivial?
Not an option when
doStuff();
returnsvoid
.Obliges
doStuff();
to return a value now and in the future.
When competing options exist, code for maintenance and clarity.
Winner here:
if (my_flag) {
doStuff();
}
If the if
statement is short, optionally omit the braces
if (my_flag)
doStuff();