I have a JAVA class A which has a method foo
abstract class A {
abstract void foo();
}
I also have a derived class of A - MutableA. MutableA is a singleton object indicating that no update is necessary which is useful for reusing code flows. foo() should never be called on MutableA. What is the best way to achieve that:
- Throw Unsupported exception
- Do nothing (empty implementation)
- This is a bad design what so ever.
Can someone recommend me what is the best practice in this case?
foo
is supposed to do. Any of those options might apply. – IthacaImmutable*
classes do, which is to mark such methods@Deprecated
. This doesn't stop you calling them, but at least your IDE (if you use one) can give you a hint that something is up, provided that you have a reference toMutableA
specifically. – BurlettaUnsupportedOperationException
if you call a mutating collection method on an immutable structure. They also mark the method as@Deprecated
. – LimpetBest practice for implementing a derived method that shouldn't be called
... is an oxymoron. There is no "best practice" for what is essentially a hack and violation of good inheritance design. Either implement inheritance correctly, or favour composition instead. Perhaps your design is too coarse grained. Of course, you can ignore what I've just said if you're stuck with some horrible legacy codebase/api where all sensibilities are thrown out the window – Amorino