Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct behavior for interface methods that can't be implemented

Tags:

java

If I have a class that needs to implement an interface but one or more of the methods on that interface don't make sense in the context of this particular class, what should I do?

For example, lets say I'm implementing an adapter pattern where I want to create a wrapper class that implements java.util.Map by wrapping some immutable object and exposing it's data as key/value pairs. In this case the methods put and putAll don't make sense as I have no way to modify the underlying object. So the question is what should those methods do?

like image 234
Mike Deck Avatar asked Oct 07 '08 17:10

Mike Deck


2 Answers

Any method that cannot be implemented according to the semantics of the interface should throw an UnsupportedOperationException.

like image 110
Mike Deck Avatar answered Sep 18 '22 13:09

Mike Deck


That depends on your business case. 2 options:

  • Do nothing.
  • Throw an UnsupportedOperationException.

Use whichever makes more sense. If you do nothing, you are not obeying the contract of the interface. However, throwing a runtime exception can wreak havoc on the calling code. Thus, the decision will have to be made based on how you will be using the class. Another option would be to use a simpler or different interface, if possible.

Do note that the Java library goes the exception route in the specific case of read-only collections.


It was noted below that UnsupportedOperationException is a part of the java collections framework. If your situation is outside of collections, and the semantics bother you, you can roll your own NotImplementedException, or if you are already using commons-lang, you could use theirs.
like image 37
Chris Marasti-Georg Avatar answered Sep 18 '22 13:09

Chris Marasti-Georg