On Sunday, October 6, 2002, at 06:17  PM, Daniel B. Boorstein wrote:
[SNIP]

> I think there may be some confusion here. In java, there's no special 
> syntax
> to declare a method an optional part of the interface. All concrete 
> classes
> that implement the Collection interface still must define full-bodied
> C<add(Object element)> methods. It just so happens that by convention 
> some
> classes simply throw an UnsupportedOperationException, perhaps like so:
>
> public class MyStaticCollection implements Collection {
>   ...
>   public boolean add (Object element) {
>     throw new UnsupportedOperationException("add not supported");
>   }
>   ...
> }

        Yes, this is true and is a common way to stub out methods you may 
choose not to provide functionality for. For example, your code 
implements a JDK 1.2 interface, then you subsequently switch to the 1.4 
VM implementation for which that interface's API has changed and there 
are now 14 more methods to be implemented for which you don't care 
about :-) You still need to provide the method signatures in your 
concrete class, but as in your example above you can throw an 
UnsupportedOperationException within that method.  Or as Michael 
pointed out in the Collections interface, the add() method of a 
read-only Collection implementation will throw an 
UnsupportedOperationException.

        I wouldn't call it a dirty little secret as Michael put it :-).  This 
is the right thing to do within the context of a contract. The contract 
does not guarantee that method functionality implemented by a concrete 
class does exactly a certain thing a certain way ( I'd like to see the 
language that does!). It only guarantees return type, optional 
parameters to accept and any CHECKED exceptions that need be thrown 
(and _importantly_, caught by the invoker), not actually what goes on 
in the method. If it did it wouldn't be an interface :-) Now, an 
UnsuppoertedOperationException is an UNCHECKED (subclass of 
RuntimeException) exception.

        The weakness if any lies here. It would be nice for the compiler to 
tell me that I've invoked a method which is going to throw that 
exception, so I would know that I used a method that I probably 
shouldn't be using before it actually gets tapped at runtime which is 
too late and goes *boom*.

-Noah


Reply via email to