A common cause of bad readability is nested if statements, especially when they could be combined into one if with an AND (&&). This also opens the opportunity to extract private methods to make the if more readable. While you’re at it, you might also want to rearrange the expressions so they make more logical sense.
But making these changes can be tedious and time consuming and often error-prone. It may not happen that frequently, but when it does you want it to go as fast as possible.
Eclipse comes to the rescue with a quick fix that allows you to join or split the statements in one keystroke. And the quick fix allows you to rearrange expressions on the if statement as well.
How to join and split if statements
To join if statements, stand on the outer level if (the actual word) and press Ctrl+1 (Quick Fix). Choose the entry Join ‘if’ statement with inner ‘if’ statement. Done. You can also stand on the inner if and choose join with outer.
To split if statements, stand on the logical expression’s operator (eg. the &&) and press Ctrl+1. Choose Split && condition. Eclipse creates 2 if-statements and nests the one in the other.
Watch the video to see how easy it is to join or split if-statements using Quick Fix. The example uses a string empty check that checks for null and non-zero length.
But that’s not all you can do with if statements
As a bonus, you can also do other things to if statements using Quick Fix. Try the following:
- Swap expressions in an AND (&&) or OR (||) to make the if more readable or fix a short circuit evaluation bug. Stand on the operator (eg. &&), press Ctrl+1 and choose Exchange left and right operands for infix expression. This works on any expression (eg. in return statements and while loops), but may be most useful in if statements.
- For nested if‘s, you can swap the inner and outer if statements. Simply stand on the if keyword of the second, inner if, press Ctrl+1 and choose Exchange conditions for inner and outer ‘if’ statements.
- If you want to keep your sanity and put braces around a single line if statement, press Ctrl+1 on the if keyword and choose Change ‘if’ statement to block. You can also let Eclipse automatically add braces to single line if statements every time you save.
- You can also reverse the above (ie. remove braces from single line if), but would you really want to do that?
The video below shows an example of each of the above:
Related Tips
- Convert nested/anonymous classes into top level classes using Eclipse refactoring
- Extract constants from strings and numbers with Eclipse refactorings
- Add, remove and reorder a method’s arguments instantly across multiple classes in Eclipse
- Skip over certain classes when using Step Into in Eclipse’s debugger
- Generate static imports in Eclipse on autocomplete for JUnit Assert, StringUtils and others