1

I'm using Eclipse Neon

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

 myObj.getStatus()

E.g.

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();
...
Ori Marko
  • 56,308
  • 23
  • 131
  • 233

1 Answers1

2

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)
howlger
  • 31,050
  • 11
  • 59
  • 99
  • Thank you for answering, I was hoping for refactor to the nearest enclosing block similar to javascript's let – Ori Marko Sep 02 '18 at 14:26
  • Maybe there should be additional levels for blocks/scopes in the control box tree. But in your example, all four occurrences are not inside the if-statement body and therefore in the same block/scope. There should be one group for each, before and after `myObj.changeMe()`, but how to know that `myObj.changeMe()` changes the value of the extracted variable? – howlger Sep 02 '18 at 14:50
  • add an enhancement https://bugs.eclipse.org/bugs/show_bug.cgi?id=538518 – Ori Marko Sep 03 '18 at 04:11
  • I have a another question about eclipse https://stackoverflow.com/questions/49716180/eclipse-auto-import-java-util-classes-on-ambiguous-imports – Ori Marko Sep 03 '18 at 06:32