I need to deprecate APIs in a Java SDK to make them more general. But I can't figure out how to do it for the following case:
public class AdoptDog {
public interface OnDogAdoption {
public void onDogAdoption(String dogName);
}
public void adoptDog(final String dogName, OnDogAdoption callbackObj) {
// Perform asynchronous tasks...
// Then call the callback:
callbackObj.onDogAdoption(dogName);
}
}
Users of the SDK make calls as follows:
AdoptDog adoptDog = new AdoptDog();
adoptDog.adoptDog("Snowball", new OnDogAdoption {
@Override
public void onDogAdoption(String dogName) {
System.out.println("Welcome " + dogName);
}
};
I want to generalize from Dog to Pet and deprecate APIs that mention Dog. For backward compatibility, the code snippet above where Snowball gets adopted should not have to change when I deprecate the APIs.
How I tried to deprecate the Dog API:
// Introduce Pet API
public class AdoptPet {
public interface OnPetAdoption {
public void onPetAdoption(String petName);
}
public void adoptPet(final String petName, OnPetAdoption callbackObj) {
// Perform asynchronous tasks...
// Then call the callback:
if (callbackObj instanceof OnDogAdoption) {
((OnDogAdoption) callbackObj).onDogAdoption(petName);
}
else {
callbackObj.onPetAdoption(petName);
}
}
}
// Dog API now extends Pet API for backward compatibility
@Deprecated
public class AdoptDog extends AdoptPet {
@Deprecated
public interface OnDogAdoption extends AdoptPet.OnPetAdoption {
@Deprecated
public void onDogAdoption(String dogName);
}
@Deprecated
public void adoptDog(final String dogName, OnDogAdoption callbackObj) {
super.adoptPet(dogName, callbackObj);
}
}
The problem is it's not fully backward compatible. Users of the SDK have to implement AdoptPet.OnPetAdoption.onPetAdoption() or else they get a compiler error:
AdoptDog adoptDog = new AdoptDog();
adoptDog.adoptDog("Snowball", new OnDogAdoption {
@Override
public void onDogAdoption(String dogName) {
System.out.println("Welcome " + dogName);
}
// PROBLEM: How avoid customers having to implement this dummy method?
@Override
public void onPetAdoption(String petName) {
assert("This code should not be reached");
}
};
Is there some other way to deprecate AdoptDog
(specifically OnDogAdoption
) and maintain full backward compatibility?