Reputation: 193
I would like to refactor a few if
statements I've encountered in some legacy code, to make them easier to read.
For example:
if (condition1 || condition2 || condition3 || condition4 || condition5 || condition6 || condition7)
I thought about maybe store the long condition list in a variable, give it a descriptive name and use that variable name in the if
statement.
Upvotes: 0
Views: 52
Reputation: 700
I think the good approach in this case is Consolidate Conditional Expression. You can combine all conditions in one function.
function isConditionsCorrect() {
return (condition1)
|| (condition2)
|| (condition3)
|| (condition4)
|| (condition5)
|| (condition6);
}
if (isConditionsCorrect()) return 0;
Upvotes: 0
Reputation: 22265
Having readable code is above all a question of presentation
you can do
if ( (condition1)
|| (condition2)
|| (condition3)
|| (condition4)
|| (condition5)
|| (condition6)
) {
// something to do...
}
or:
(dark and obscure method reserved for members of the sect of demonic coders)
switch (true) {
case (condition1):
case (condition2):
case (condition3):
case (condition4):
case (condition5):
case (condition6):
// something to do...
break;
}
[edit]
You can also use an indent to show the hierarchy of conditions:
if ( (condition1)
|| (condition2)
|| ( (condition3-1)
&& (condition3-2)
&& (condition3-3)
)
|| (condition4)
|| (condition5)
|| (condition6)
) {
// something to do...
}
Upvotes: 2