Which of the two, do you think, is better?
if (the_condition) { variable = sth; } else { variable = sth_else; } if (the_condition) { variable_2.doSth(); } else { variable_2.doSthElse(); }
or
if (the_condition) { variable = sth; variable_2.doSth(); } else { variable = sth_else; variable_2.doSthElse(); }
I ask about it because the second example is obviously shorter. On the other hand in the first example operations on different variables are separated, thus probably easier to read.
Do you consider any of them better? Or is it pointless to ask such a question as it does not matter?
What if the condition changes? Then you'd have to update it in n places! (And it's easy to miss one, introducing subtle, hard-to-find bugs.)
I personally find #1 much harder to read, since I have to read the condition for each assignment because it might be different. With #2, I know that everything in the if
body is in the context of a single condition -- you might say that the condition encapsulates a single, cohesive multi-statement chunk of behaviour.
Of course, if the statements in the body of an if
are unrelated (i.e. not part of the same chunk of behaviour), then they should be in separate if
s. That's probably not the case here, though: You're setting up variables depending on an initial condition (which is likely one logical operation).
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