I have a hierarchy, which I'll simplify greatly, of implementations of interface Value. Assume that I have two implementations, NumberValue, and StringValue.
There is an average operation which only makes sense for NumberValue, with the signature
NumberValue average(NumberValue numberValue){
...
}
At some point after creating such variables and using them in various collections, I need to average a collection which I know is only of type NumberValue, there are three possible ways of doing this I think:
Very complicated generic signatures which preserve the type info in compile time (what I'm doing now, and results in hard to maintain code)
Moving the operation to the Value level, and: throwing an unsupportedOperationException for StringValue, and casting for NumberValue.
Casting at the point where I know for sure that I have a NumberValue, using slightly less complicated generics to insure this.
Does anybody have any better ideas, or a recommendation on oop best practices?