Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring - Collapsible "if" statements should be merged

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

like image 492
Srikanth A Avatar asked Sep 20 '25 00:09

Srikanth A


2 Answers

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.

like image 94
Bas Leijdekkers Avatar answered Sep 21 '25 13:09

Bas Leijdekkers


The AutoRefactor Eclipse plug-in can do this for you in batch.

See http://autorefactor.org/html/samples.html and select CollapseIfStatementSample.java. You can do this on a whole file, package, or even project.

There is a refactoring to remove unnecessary parentheses too: SimplifyExpressionSample.java (see e. g. line 144).

like image 36
JnRouvignac Avatar answered Sep 21 '25 14:09

JnRouvignac