Generally, yes. However, you must be aware of surprises, some of which I mention next.
Disclaimer: none of these lists is exhaustive.
Badly designed interfaces:
- with lots of methods;
- with methods that don't throw sensible exception types, or methods that don't throw at all (a problem in checked exception languages like Java: when not given a second thought, most people usually throw
Exception or nothing);
- with methods that may not be implemented, in the sense that they can throw
UnsupportedOperationException (an unchecked exception) or a subclass of it (in .NET, there's already a more explicit NotImplementedException); usually seen together with huge interfaces.
What can be done:
- Split the huge interfaces;
- Provide at least one subclass of
Exception in the same namespace as the interface;
- If you cannot split an interface for some good reason, state clearly which methods may throw a
UnsupportedOperationException (or NotImplementedException in .NET). It may be all methods, but state it clearly, such as at the head of the interface's documentation or in a separate small paragraph near the top, and also in each method's description.
If you must use a huge interface which describes what methods may throw unchecked exceptions such as UnsupportedOperationException (I'm assuming it's an interface out of your control), be ready to catch them or document that your methods may throw them.
An interface should be as small as possible and its implementation should mean it's totally implemented. In the real world, however, it's not always the case, and sometimes one has to go through hoops.
A bad class implementation:
- that implements an interface on the interest of supporting only part of its contract, like one or two of its methods, usually doing nothing or returning non-sense for all other methods (unless it's actually implementing an observer);
- that throws
UnsupportedOperationException (or NotImplementedException in .NET) in methods where the interface doesn't clearly state that it may be thrown;
What can be done:
- Have an abstract class that implements most boilerplate, and either inherit from it directly, or create a subclass of it and use this new class to instantiate delegation objects. In fact, many Java observer objects already come with this facility, even though the default implementation of all its methods is to do absolutely nothing.
- Correct it, follow the contract. If the code is not yours, try to wrap such misbehaviour.