Refactoring - Folding "if" statements need to be combined

I am trying to clean up our legacy code and noticed that there are many conditional codes that can be combined.

Example -

if (file != null) {
  if (file.isFile() || file.isDirectory()) {
    /* ... */
  }
}

      

It can be refactored,

if (file != null && (file.isFile() || file.isDirectory())) { 
  /* ... */
}

      

Manually making this change is a pain. So, I was trying to test the template validation and refactoring tool in intelliji to help me with this bulk code refactoring.

Couldn't find this Eclipse environment either.

Please suggest if there is an option in Intelliji / Eclipse for this

+3


source to share


2 answers


In IntelliJ IDEA, place the text cursor on the first keyword if

, press Alt+ Enterand invoke Merge nested 'if's

.

You can also use Structured Search and Replace to do this 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 amount statement

to 0,∞

. Also set the min and max values void

to0,0



Use the following replacement pattern:

if (($a$) && ($b$)) {
  $statement$;
}

      

Note that in some cases this replacement will result in redundant parentheses to prevent changes to the semantics of the code. They can then be deleted again by calling Run Inspection by Name

and checking Unnecessary parentheses

.

+1


source


AutoRefactor An Eclipse plugin can do this for you in batch.

See http://autorefactor.org/html/samples.html and select CollapseIfStatementSample.java

. You can do this for an entire file, package, or even a project.



There is also refactoring to remove unnecessary parentheses: SimplifyExpressionSample.java

(see, for example, line 144).

+2


source







All Articles