I have a class that, in some scenarios, updates it's internal state permanently, and in other scenarios, calculates a projected value. The process of updating the internal state is the same as the process of calculating the projected value, but because one works with local variables and one works with fields I don't see a way to avoid copy/pasting of code.
I think the problem is because foo
and bar
are primitives, which means they can't be updated by reference. But for an example as simple as this one does it make sense to wrap foo
and bar
in an inner class
?
public abstract class RatioUpdate {
private double foo;
private double bar;
public Update(double foo, double bar) {
this.foo = foo;
this.bar = bar;
}
public double getRatio() {
return foo / bar;
}
public double updateData(double input) {
foo = recalculateFoo(foo, input);
bar = recalculateBar(bar, input);
return foo / bar;
}
public double getProjectedRatio(double input) {
double newFoo = recalculateFoo(foo, input);
double newBar = recalculateBar(bar, input);
return newFoo / newBar;
}
// Abstract because not really relevant, this was the best I could do to avoid duplication
protected abstract recalculateFoo(double foo, double input);
protected abstract recalculateBar(double bar, double input);
}