In a application data entry, I allow the user to insert a numeric value that can represent two different things:
- an absolute value, say 5, meaning that a property P should be assigned the value 5
- a relative value, say +5, meaning that the property P should be incremented by 5
My question is: which data-structure use to store this inforation?
I lay down some alternatives.
My idea is going with the 3rd idea, but I wonder is the pattern is “correct”.
1)
Here the absolute xor the increment is assigned, the other left null. Not very satisfactory.
class DoubleFieldBased {
Integer absolute;
Integer increment;
}
2)
Here the “magnitude” of the value is saved into “value”, while the boolean “increment” tells wheter the value is absolute or relative. Even less satisfactory.
class FieldAndBoolean {
Integer value;
boolean increment;
}
3)Here I move the focus to the method applyValue, that uses polymorphism and do the right thing based on the implicit information of what class “am I”. Satisfactory but a bit complex, and I suspect the pattern isn’t perfect.
public static abstract class AbstractValue {
int myvalue;
public AbstractValue (int myvalue) {this.myvalue = myvalue;}
public abstract int applyValue (int value);
}
public static class Absolute extends AbstractValue {
public Absolute (int myvalue) {super(myvalue);}
public int applyValue (int value) {
return value;
}
}
public static class Incremental extends AbstractValue {
public Incremental (int myvalue) {super(myvalue);}
public int applyValue(int value) {
return myvalue + value;
}
}
I’d say use an Integer or other numeric type) and an enum, something like this:
You could even use the enum as strategy: