Handling a binary operation that makes sense only for part of a hierarchy.

Posted by usersmarvin_ on Stack Overflow See other posts from Stack Overflow or by usersmarvin_
Published on 2010-05-05T13:44:01Z Indexed on 2010/05/05 13:48 UTC
Read the original article Hit count: 165

Filed under:
|

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:

  1. Very complicated generic signatures which preserve the type info in compile time (what I'm doing now, and results in hard to maintain code)
  2. Moving the operation to the Value level, and: throwing an unsupportedOperationException for StringValue, and casting for NumberValue.
  3. 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?

© Stack Overflow or respective owner

Related posts about java

Related posts about oop