boolean (@NotNull PsiIfStatement ifStatement, @NotNull List<? extends ExtractionUnit> units, @NotNull PsiElementFactory factory, @NotNull Map<PsiLocalVariable, String> substitutionTable, @NotNull CommentTracker ct) { // collect replacement info Map<PsiReferenceExpression, String> referenceToNewName = new HashMap<>(); Map<PsiLocalVariable, String> variableToNewName = new HashMap<>(); for (ExtractionUnit unit : units) { if (unit instanceof VariableDeclarationUnit declarationUnit) { PsiLocalVariable thenVariable = declarationUnit.myThenVariable; PsiLocalVariable elseVariable = declarationUnit.myElseVariable; String baseName = substitutionTable.get(elseVariable); JavaCodeStyleManager manager = JavaCodeStyleManager.getInstance(ifStatement.getProject()); if (baseName != null) { Predicate<PsiVariable> canReuseVariable = var -> PsiTreeUtil.isAncestor(ifStatement, var, false); String nameToBeReplacedWith = manager.suggestUniqueVariableName(baseName, ifStatement, canReuseVariable); for (PsiReference reference : ReferencesSearch.search(thenVariable, new LocalSearchScope(ifStatement))) { PsiReferenceExpression expression = (PsiReferenceExpression)reference.getElement(); referenceToNewName.put(expression, nameToBeReplacedWith); } for (PsiReference reference : ReferencesSearch.search(elseVariable, new LocalSearchScope(ifStatement))) { PsiReferenceExpression expression = (PsiReferenceExpression)reference.getElement(); referenceToNewName.put(expression, nameToBeReplacedWith); } variableToNewName.put(thenVariable, nameToBeReplacedWith); variableToNewName.put(elseVariable, nameToBeReplacedWith); declarationUnit.myNewVariableName = nameToBeReplacedWith; } else { declarationUnit.myNewVariableName = thenVariable.getName(); } } } // do actual replace (can't be done in collection loop, because it can affect resolve) referenceToNewName.forEach((reference, newName) -> ExpressionUtils.bindReferenceTo(reference, newName)); variableToNewName.forEach((variable, newName) -> variable.setName(newName)); PsiElement parent = ifStatement.getParent(); for (ExtractionUnit unit : units) { PsiStatement statement = unit.getStatementToPutBeforeIf(factory, ifStatement); parent.addBefore(statement, ifStatement); unit.cleanup(ct, factory, ifStatement); } return true; }