I have a situation where multiple classes can extend one core class. There's a property (say, isAtomic
), which in some subclasses will depend on the data but in other subclasses will constantly be true
. I'd like, if possible, the check to be as inexpensive as possible in the latter case. I can think of several approaches:
The obvious:
abstract bool isAtomic()
which would be implemented toreturn true/false
in the "constant" subclasses,A subclass
Atomic extends Base
which would implementisAtomic()
asreturn true;
and which the other "constant" subclasses would extend (probably not too much different from 1),The base class implementing
isAtomic
asreturn true;
and the non-constant subclasses overriding this definition,An interface
Atomic
implemented by the atomic subclasses which would obviously not return anything but would be checked against usingx instanceof Atomic || x.isAtomic()
.
I'm not too experienced in OOP but something tells me that the last approach represents the concept nicely and saves a function call, even though the more complicated usage. But I don't know whether an instanceof
is indeed "cheaper" than calling a function. 3 should be quicker than 1 or 2 but feels against the nature of the isAtomic
function. What do the experts say? Or is there another intuitive way, better than those listed, I didn't think of?