Description
Move Instance Method changes the behavior of the program when moving the instance method process() from class A to class C.
Before refactoring, process() checks whether the field c is null. Since a.c is null in the original program, the method safely returns 0.
After moving the instance method process() to class C, VS Code Java changes the call site from:
to:
However, a.c is null, so the refactored program throws NullPointerException before the moved method is entered.
In addition, the original condition:
is rewritten as:
if (this != null) return 2;
This is not semantically equivalent. The original condition checks whether the source object's field c is null, while this != null is effectively always true once the instance method is entered.
Code before refactoring
public class t {
public static void main(String[] args) {
A a = new A();
System.out.println(a.process());
}
}
class A {
C c;
// Move Instance Method target method
int process() {
if (c != null) return 2;
return 0;
}
}
class B extends A { }
class C extends B { }
Before refactoring, the program prints:
Refactoring operation
Apply Move to method A.process() and move it to class C.
Code after refactoring
public class t {
public static void main(String[] args) {
A a = new A();
System.out.println(a.c.process());
}
}
class A {
C c;
}
class B extends A { }
class C extends B {
int process() {
if (this != null) return 2;
return 0;
}
}
After refactoring, running the program throws:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "C.process()" because "<local1>.c" is null
at t.main(t.java:4)
Description
Move Instance Methodchanges the behavior of the program when moving the instance methodprocess()from classAto classC.Before refactoring,
process()checks whether the fieldcis null. Sincea.cis null in the original program, the method safely returns0.After moving the instance method
process()to classC, VS Code Java changes the call site from:to:
However,
a.cis null, so the refactored program throwsNullPointerExceptionbefore the moved method is entered.In addition, the original condition:
is rewritten as:
This is not semantically equivalent. The original condition checks whether the source object's field
cis null, whilethis != nullis effectively always true once the instance method is entered.Code before refactoring
Before refactoring, the program prints:
Refactoring operation
Apply
Moveto methodA.process()and move it to classC.Code after refactoring
After refactoring, running the program throws: