We will use the same A, B and C classes as in the previous example
. The goal is to insert a new class with additional members between B and C class in the hierarchy.
Let's store some class objects first:
01public static void storeData(){ 02
new File(DB4O_FILE_NAME).delete(); 03
ObjectContainer container = Db4o.openFile(DB4O_FILE_NAME); 04
try { 05
A a = new A(); 06
a.name = "A class"; 07
container.set(a); 08
09
B b = new B(); 10
b.name = "B class"; 11
b.number = 1; 12
container.set(b); 13
14
C c = new C(); 15
c.name = "C class"; 16
c.number = 2; 17
container.set(c); 18
} finally { 19
container.close(); 20
} 21
}
01public static void readData(){ 02
ObjectContainer container = Db4o.openFile(DB4O_FILE_NAME); 03
try { 04
ObjectSet result = container.get(new A()); 05
System.out.println("A class: "); 06
listResult(result); 07
08
result = container.get(new B()); 09
System.out.println(); 10
System.out.println("B class: "); 11
listResult(result); 12
13
result = container.get(new C()); 14
System.out.println(); 15
System.out.println("C class: "); 16
listResult(result); 17
} finally { 18
container.close(); 19
} 20
}
The following class will be inserted:
01/* Copyright (C) 2007 db4objects Inc. http://www.db4o.com */ 02
package com.db4odoc.refactoring.refactored; 03
04
import java.util.Date; 05
06
import com.db4odoc.refactoring.initial.B; 07
08
public class D extends B { 09
public Date storedDate; 10
11
public String toString(){ 12
return name + "/" + number + ": " + storedDate; 13
} 14
}
Now C class must inherit from D. We can't change C class itself, because its data will be lost. Therefore we will create a new E class to hold C data:
1/* Copyright (C) 2007 db4objects Inc. http://www.db4o.com */ 2
package com.db4odoc.refactoring.refactored; 3
4
public class E extends D { 5
6
}
When all the necessary classes are created we can copy C data into E class:
01public static void moveValues(){ 02
ObjectContainer container = Db4o.openFile(DB4O_FILE_NAME); 03
try { 04
ObjectSet result = container.get(new C()); 05
while (result.hasNext()){ 06
C c = (C)result.next(); 07
E e = new E(); 08
e.name = c.name; 09
e.number = c.number; 10
container.delete(c); 11
container.set(e); 12
} 13
14
} finally { 15
container.close(); 16
System.out.println("Done"); 17
} 18
}
Now C classes can be safely removed from the project and all the references to it updated to E(or D). We can check that all the values are in place:
01public static void readData(){ 02
ObjectContainer container = Db4o.openFile(DB4O_FILE_NAME); 03
try { 04
ObjectSet result = container.get(new D()); 05
System.out.println(); 06
System.out.println("D class: "); 07
listResult(result); 08
09
result = container.get(new E()); 10
System.out.println(); 11
System.out.println("E class: "); 12
listResult(result); 13
} finally { 14
container.close(); 15
} 16
}
When performing refactoring on your working application do not forget to make a copy of the code and data before making any changes!