Search code examples
javainterfacedefault-methodunsupportedoperation

Default method with UnsupportedOperationException implementation


I need to fix a bug in my project, but it turns out the root cause is an effect of many workarounds spread for all implementations of an interface due to a design problem. I want to refactor that interface, but I can't do it now, cause I don't have time to change all implementations. So my ideia is to add a default method in this interface and implement it in only one implementation (partially fixing the design problem) and then making the big refactoring in next sprint. This refactoring is about replacing all methods in this interface for simpler and more meaningful ones. One of those new methods is the default method which the question is about.

But actually there is no implementation needed for this method, its just a temporary solution which goes to the right direction.

Does it make sense to implementing that default method (in the interface, of course) throwing an UnsupportedOperationException?


Solution

  • The whole idea behind default methods is to provide for adding methods to an interface without automatically breaking existing implementations. It seems like that is what you propose to do, so that makes sense as far as it goes.

    But in comments you remarked:

    I'm gonna override it in the implementation class that I need to fix the bug and then call this new method instead of the previous one which doesn't make sense.

    If you are going to be invoking the new method on any instance of your interface, then you need to be confident that it will do something appropriate. If there's any chance that such an invocation is served by your proposed default implementation that always throws UnsupportedOperationException (and supposing that would be undesirable), then that probably does not justify such confidence.

    If you somehow do have justified confidence that the new method will be invoked only on instances of one specific implementation class then either there is something very strange about the way you are using interfaces, or you don't actually need to change the interface at all. That is, if you know what implementation you are working with, you can add the new method to that class alone, without changing the interface.