Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java API break

I have the following API:

public interface MyApi {

   /**
    * Performs some stuff.
    * @throws MyException if condition C1
    */
   public void method() throws MyException;
}

I am now performing the following modification in my API implementation

public class MyApiImpl {

   public void method() throws MyException {
     if (C1) {
       throw new MyException("c1 message");
     }
     ...
   }
}

is replaced by :

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 consider this as an API breakage ?

Client's code will still compile but method contract defined by the API javadoc is no more respected since MyExcepiton is thrown by a "new" condition.

If only my API jar file is updated, clients application will still work but depending on the way clients catch the exception the application behavior can change a lot.

What's your point of view on that ?

like image 284
Manuel Selva Avatar asked Jun 24 '09 13:06

Manuel Selva


4 Answers

Yes, you're breaking the contract of the interface by throwing an exception when C1 doesn't occur.

As a rule of thumb, the vaguer the interface contract, the easier it is not to break :) If the interface isn't defined in terms of an explicit C1, but in more general terms, that gives a lot more flexibility.

like image 81
Jon Skeet Avatar answered Sep 29 '22 02:09

Jon Skeet


My point of view is that you should not change the contract defined by the API in the documentation. If you need new behavior you should either a.) create a new method that can be called by the client reflecting this new behavior or b.) discuss with the client the need for the change and make them aware of it.

This really can go both ways, it is between you and your clients as to what your approach will be.

like image 33
amischiefr Avatar answered Sep 29 '22 01:09

amischiefr


It largely depends on what c2 is. Is it within the logical bounds on the pre-existing contract? If so, you're satisfying the contract by throwing a MyException. If not then perhaps you need to throw a new type of exception.

I should point out that I'm not a huge fan of checked exceptions. Ultimately, forcing someone to deal with an exception doesn't necessarily make their code any better or safer (in fact it can have the opposite effect as they can sloppily swallow spurious exceptions).

like image 26
cletus Avatar answered Sep 29 '22 00:09

cletus


I'd say "no", no API breakage, unless MyException is a RuntimeException. Then it is.

Anyway, I'd subclass MyException for condition C2

And both conditions C1 and C2 should be "exceptional" IMHO, I would not make an habit of throwing exceptions

like image 34
Diego Amicabile Avatar answered Sep 29 '22 00:09

Diego Amicabile