Defending UnsupportedOperationException
I just listened to super-smart guy Elliot Rusty Harold critique the Java Collections API on his recent Javapolis interview:In the Java Collections API, I really do not like the UnsupportedOperationsExceptions. I do not like that given a list I don't know whether I can actually add something to this list or not. I don't know how it behaves by virtue of it's being a list. I don't know whether the methods it advertises actually work or don't. That bothers me a lot.
I think that UnsupportedOperationExceptions are a reasonable solution to a difficult problem. The Java Collections API Design FAQ describes in detail why UnsupportedOperationException is the lesser of two evils.
I'm not sure why Mr. Harold is so offended by UnsupportedOperationException - just like NullPointerException, all occurences of it should be found and fixed during testing. I love using UnsupportedOperationException in my code! Frequently I'll extend the
Format
class, which is intended to convert objects to Strings and back. It has two abstract methods: format(...)
to convert objects to Strings, and parseObject(...)
to convert Strings to objects. When I don't need parsing, I can simply throw UnsupportedOperationException() from the parseObject()
method.