Looking through the Java Collections Framework, I've noticed quite a few of the interfaces have the comment (optional operation)
. These methods allow implementing classes to through an UnsupportedOperationException
if they just don't want to implement that method.
An example of this is the addAll
method in the Set Interface
.
Now, as stated in this series of questions, interfaces are a defining contract for what the use can expect.
Interfaces are important because they separate what a class does from how it does it. The contract defining what a client can expect leaves the developer free to implement it any way they choose, as long as they uphold the contract.
and
An interface is a description of the actions that an object can do... for example when you flip a light switch, the light goes on, you don't care how, just that it does. In Object Oriented Programming, an Interface is a description of all functions that an object must have in order to be an "X".
and
I think the interface-based approach is significantly nicer. You can then mock out your dependencies nicely, and everything is basically less tightly coupled.
What is the point of an interface?
Interface + Extension (mixin) vs Base Class
Given that the purpose of interfaces is to define a contract and make your dependencies loosely coupled, doesn't having some methods throw an UnsupportedOperationException
kind of defeat the purpose? It means I can no longer be passed a Set
and just use addAll
. Rather, I have to know what implementation of Set
I was passed, so I can know if I can use addAll
or not. That seems pretty worthless to me.
So what's the point of UnsupportedOperationException
? Is it just making up for legacy code, and they need to clean up their interfaces? Or does it have a more sensical purpose that I'm missing?