Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two separate "if"'s, same condition -- is it OK? [closed]

Tags:

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?

like image 587
sthlm58 Avatar asked Jul 11 '11 12:07

sthlm58


1 Answers

#2

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 ifs. That's probably not the case here, though: You're setting up variables depending on an initial condition (which is likely one logical operation).

like image 122
Cameron Avatar answered Dec 02 '22 21:12

Cameron