I am trying to clean up our legacy code, and noticed there are many if conditional code that can be merged.
Example -
if (file != null) {
if (file.isFile() || file.isDirectory()) {
/* ... */
}
}
This can be refactored to,
if (file != null && (file.isFile() || file.isDirectory())) {
/* ... */
}
Manually performing this change is a pain. So, I was trying to check on inspection tool and template refactoring in intelliji to help me with this bulk code refactoring.
Could not locate this eclipse IDE too.
Kindly suggest, is there an option in Intelliji/Eclipse for this
In IntelliJ IDEA put the text cursor on the first if
keyword, press Alt+Enter and invoke Merge nested 'if's
.
You can also use Structural Search & Replace to perform this operation in bulk. Use the following search pattern:
if ($a$) {
if ($b$) {
$statement$;
} else $void$;
} else $void$;
Click Edit Variables...
and set the minimum and maximum count of statement
to 0,∞
. Also set the minimum and maximum count of void
to 0,0
Use the following replacement pattern:
if (($a$) && ($b$)) {
$statement$;
}
Note that this replacement will introduce redundant parentheses in some cases to prevent changes the semantics of the code. These can later be removed again by invoking Run Inspection by Name
and running the Unnecessary parentheses
inspection.