What's the right way to design my interface when I have operations that aren't supported by all implementers?
You should do one of the following:
Break up the interface into smaller pieces and compose as needed. This is the preferred approach, especially if you control
MyInterface
.Return the most sensible default value that you can.
Throw an
UnsupportedOperationException
.
Here's a more illustrative example. Let's say your interface looks like this:
public interface Driveable {
public Position accelerate(Vector v, Time t);
public String getVehicleIdentificationNumber();
}
If your MyClass1
is actually a Boat
and doesn't have a vehicle identification number, then it doesn't make sense for you to implement this. In fact, it's actually wrong. Other clients expect you to have this value, but you can't give it to them.
It would be better to chunk and compose the interfaces into smaller pieces, using the right slice as necessary. For example, you might instead write this:
public interface Driveable {
public Position accelerate(Vector v, Time t);
}
public interface Vehicle extends Driveable {
public String getVehicleIdentificationNumber();
}
public class Boat implements Driveable { ... }
public class Car implements Vehicle { ... }
This is the best approach since it segments the responsibilities exactly as needed across the interfaces.
If it really was important in your domain for all Driveables to have a vehicle identification number, and this is just a special case where the vehicle identification number is unknown or not available, then you can provide a default implementation:
public String getVehicleIdentificationNumber() {
return "";
}
If it would be wrong in your domain to return a vehicle identification number at all, then you should throw an exception:
public String getVehicleIdentificationNumber() {
throw new UnsupportedOperationException("vehicle identification
number not supported on boats");
}
If you still need it in the interface and it never should be called (in that implementation) I would implement make it throw an UnsupportedOperationException:
public int secondMethod() {
throw new UnsupportedOperationException("Should not be called!");
}
If there are irrelevant methods for you:
- maybe you shouldn't use this interface, consider changing the design.
- Add stub methods (as you did).