DaBlick
DaBlick

Reputation: 968

IntelliJ Refactor to pull variable definition outside it's currently block

Does IntelliJ IDEA for Java have a refactor function that can automatically move a variable definition from within a block to outside a block and refactor the definition inside the block to be a reference.

In short, turn this:

try {
    IndexResponse indexResponse = elkService.post(pipelineModel);
}

Into this:

IndexResponse indexResponse = null;
try {
    indexResponse = elkService.post(pipelineModel);
}

I find myself doing this quite frequently. The "surround by" refactors are smart about this in that if do NOT yet have the surrounding element (try/catch, if/then, etc.) and the code you want to surround defines variables that are used outside the surround-bound code, it will define the variable outside the block.

What I'm trying to do is refactor code where I INTRODUCE a reference outside an already-existing block.

Not the end of the world, to do this manually, but I was wondering if such a thing exists and/or if others wished for it.

Upvotes: 2

Views: 160

Answers (2)

Tagir Valeev
Tagir Valeev

Reputation: 100239

Since IntelliJ IDEA 2021.3 (EAP builds are already available) it's possible just to complete the variable outside of try block to bring it into the scope:

try {
  IndexResponse indexResponse = elkService.post(pipelineModel);
}
catch(Exception exception) {}
inde|

Just start typing the variable name, then invoke the completion explicitly (with Ctrl+Space), and it will be brought into the scope automatically:

IndexResponse indexResponse = null;
try {
  indexResponse = elkService.post(pipelineModel);
} catch (Exception exception) {
}
indexResponse

Disclosure: I'm IntelliJ IDEA developer responsible for implementation of this feature.

Upvotes: 5

Bas Leijdekkers
Bas Leijdekkers

Reputation: 26492

What I do is I just reference the variable outside of the block. This will of course be highlighted as an error. I can then type Alt+Enter on the error and invoke the Bring 'X x' into scope quick-fix, which will move the variable definition, but leave the assignment.

Bring variable into scope quick-fix

Upvotes: 1

Related Questions