简体   繁体   中英

Eclipse - Extract local variable replace all occurrences only in scope

I'm using Eclipse Neon

I have a repeating method calls in a over sized method:

 myObj.getStatus()

Eg

if (myObj.getStatus() == ONE || myObj.getStatus() == TWO ) {
}
myObj.changeMe();
if (myObj.getStatus() == THREE || myObj.getStatus() == FOUR) {
}
myObj.changeMe2();
...

where status can be updated internally between calls

I have only 2 options

  • Extract local variable and check the Replace all occurrences only in scope (method) which isn't good (because getStatus() isn't effectively final)

  • Extract local variable and replace manually each relevant myObj.getStatus() call

I finally Extract a method and then Extract local variable and check the Replace all occurrences

Is this the most valid option? or can I replace only in specific context/selected text in eclipse? if not can this be consider as enhancement for eclipse refactoring?

EDIT

I was hoping for refactor to the nearest enclosing block similar to JavaScript's let

Actually the code is not in same level, yet eclipse replace all occurrences in method

if (myState.equals(STATE_ONE){
  if (myObj.getStatus() == ONE || myObj.getStatus() == TWO ) {
  }
  myObj.changeMe();
}
if (myObj.getStatus() == THREE || myObj.getStatus() == FOUR) {
}
myObj.changeMe2();
...

There is a third option for that:

  1. Make sure the checkbox Replace all occurrences of the selected expression with references to the local variable is checked
  2. Click Preview >
  3. Uncheck the checkboxes where the expression should not be replaced (in your case, the last two)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM