在 Intellij 快捷方式中快速 'if-else' 翻转

Quick 'if-else' flipping in Intellij shortcut

我正在尝试重构现有的遗留代码,我注意到我有很多地方具有以下模式:

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

我想知道是否有一种快速翻转 if-else 结构的方法,可以轻松地将当前形式重构为如下形式:

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

我想去掉函数开头不必要的嵌套和检查。

将插入符号放在 'if' 上,按 Alt+Enter,select "Invert 'if' condition"从菜单中。

对于现场编辑,使用@Yole 的建议。

但是,如果您在整个项目中有很多地方,您可以使用 Edit => Find => Replace structurally 和以下模板(从 IJ 附带的示例推导并使用 v2017.3.4 测试):

搜索模板:

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

替换模板

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

$ThenStatement$;

变量:

单击 Edit variables 按钮,然后单击 select ThenStatement 变量并选中 Unlimited 框,使其应用​​于多行(或键入您需要的任何值) :

结果