Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for implementing a derived method that shouldn't be called [closed]

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:

  1. Throw Unsupported exception
  2. Do nothing (empty implementation)
  3. This is a bad design what so ever.

Can someone recommend me what is the best practice in this case?

like image 811
user844541 Avatar asked Feb 16 '15 09:02

user844541


2 Answers

I would consider rethinking the design.

Having an abstract method in the super class implies that subclasses should implement that method. Unless you plan on having a larger hierarchy in which case you should consider moving the foo method lower down in the hierarchy closer to the implementation.

If you are intent on keeping the foo methods location I would make MutableA abstract as well.

like image 72
Rickard Nilsson Avatar answered Nov 07 '22 05:11

Rickard Nilsson


You should consider havig a look at the Liskov substitution principle, which is one of the fundamental SOLID principles of good design.

The principle states that derived objects should not behave different than their parents. A common example for a violation of the Liskov principle is the derivation of a circle from an ellipse. Which is mathematically totally sensible and sound is considered to be bad design, for a circle derived from a ellipse would (for example) still expose the methods to set the width and the height, but it would behave oddly in some contexts. Consider the following

Something FooBar (Ellipse e)
{ 
    // do something with e
}

If we did not know that a caller passed a Circle rather than an Ellipse and we set both the width and the height our results may differ from what we expect, since the Circle either ignored SetHeight or it sets the width bot on SetWidth and SetHeight. Either way this behavior is unexpected if we expected to operate on an Ellipse. Hence the Liskov substitution principle.

like image 2
Paul Kertscher Avatar answered Nov 07 '22 05:11

Paul Kertscher