Tomasz Bawor
Tomasz Bawor

Reputation: 1647

Quick 'if-else' flipping in Intellij shortcut

I am trying to refactor existing legacy code and I noticed that I have many places with below pattern:

if (condition) {
    // lot of code
} else {
    throw new SomeException();
}

I was wondering if there is a fast way of flipping if-else construct to easily refactor current form to something like this:

if(!condition) throw new SomeException();
// lot of code

I want to remove unnecessary nesting and making checks at the begining of the function.

Upvotes: 29

Views: 10841

Answers (2)

yole
yole

Reputation: 97133

Put the caret on 'if', press Alt+Enter, select "Invert 'if' condition" from the menu.

Upvotes: 48

Morfic
Morfic

Reputation: 15498

For on the spot editing, use @Yole's suggestion.

However, if you have many places throughout the project, you can use Edit => Find => Replace structurally with the following templates (deduced from the samples shipped with IJ and tested with v2017.3.4):

Search template:

if ($Condition$) {
  $ThenStatement$;
} else {
  throw new $Constructor$($Argument$);
}

Replacement template

if (!$Condition$) throw new $Constructor$($Argument$);

$ThenStatement$;

Variables:

Click the Edit variables button, then select the ThenStatement variable and check the Unlimited box so it applies to multiple lines (or type whatever value you require):

Variables

Result

IJ Structural Replace

Upvotes: 18

Related Questions