I want to replace the (mutable) class
class OldValue {
private int value;
public OldValue(int value) { this.value = value; }
public int getValue() { return value; }
public void setValue(int value) { this.value = value; }
}
with the immutable class
class NewValue {
private final int value;
public NewValue(int value) { this.value = value; }
public int getValue() { return value; }
/* no setter, obviously */
}
In most parts of the code something like newValue.set(777)
can be replaced by newValue = new NewValue(777)
. However, there are some legacy parts of the code with something like
class ManagementServiceProviderFacadeSingletonAbstractFactoryObserver {
public void setTheValue(OldValue oldValue) {
oldValue.setValue(555);
}
}
class Data {
private OldValue oldValue;
public OldValue get() { return oldValue; }
}
class SomewhereElse {
public void frobnicate(Data data, ManagementServiceProviderFacadeSingletonAbstractFactoryObserver x) {
x.setTheValue(data.get());
}
}
These legacy parts are very hard to change and we would like to adapt it as little as possible. Is there a way to write some kind of "evil" setter method that could be used in the legacy code? Something like
class EvilSetter {
public static void evilSet(NewValue newValue, int x) {
// temporarily make newValue.value both public and non-final, set it to x
}
}
Is there some other way without losing the immutability and elegance of the new design?