Java API interrupt
I have the following APIs:
public interface MyApi { /** * Performs some stuff. * @throws MyException if condition C1 */ public void method() throws MyException; }
I am now performing the following modifications in the API implementation
public class MyApiImpl { public void method() throws MyException { if (C1) { throw new MyException("c1 message"); } ... } }
Replaced with:
public class MyApiImpl { public void method() throws MyException { if (C1) { throw new MyException("c1 message"); } else if (c2) { throw new MyException("c2 message"); } ... } }
Do you think this is an API violation?
The client code will still compile, but the method contract defined by API Javadoc is no longer respected because myexception is thrown by the "new" condition
If only my API jar file is updated, the client application can still work, but the application behavior may change greatly according to the way the client catches exceptions
What do you think of this?
Solution
Yes, when C1 does not happen, you break the contract of the interface by throwing an exception
According to experience, the deformation of interface contract is easier not to break:) if the interface is not defined by explicit C1, but more generally, it gives more flexibility