Video in progress
You need to change a functional interface in a public library or an internal SDK in a new version. Which changes break users, and how do you evolve it?
Adding an abstract method, changing the signature or adding an overload breaks users' lambdas at compile time or at runtime. The safe way is to add only default and static methods; if a change is needed, a new interface, with the old one kept as @Deprecated and an adapter.
📖 Answer
A functional interface is a contract. Its single abstract method is the shape of every user lambda.
What breaks:
- A new abstract method: the interface stops being functional, and all lambdas give a compile error. Code compiled against the old jar gets an
AbstractMethodErrorat runtime. - Changing a parameter or return type: breaks at both source and binary level.
- Adding a checked exception (
throws IOException): callers now have to catch it. - Adding an overload: an unexpected one. For example,
register(Handler h)existed, andregister(AsyncHandler h)was added. Nowregister(e -> process(e))can become ambiguous, because both interfaces fit that lambda. Binary compatibility isn't broken, but the user upgrades to the new version and can't compile the code.
What's safe:
defaultmethods (for exampleandThen,withTimeout): they don't affect lambdas.staticfactory methods.- New, separately named methods and interfaces.
A sample evolution:
@FunctionalInterface
public interface EventHandler {
void handle(Event e);
// v2: a context became necessary: through default, not abstract
default void handle(Event e, HandlerContext ctx) {
handle(e);
}
}
The framework now calls the two-argument method, and old lambdas keep working. For new users, a separate ContextualEventHandler interface and an adapter.
The process matters too:
- automatically check API changes in CI with
japicmporrevapi: the build fails if semver is broken; @Deprecated(since = "2.3", forRemoval = true)and a transition period of at least one minor version;- a migration example in the release notes;
- for an internal SDK, try compiling the 3–4 biggest consumer services with the new version in advance.
For APIs that rely on lambdas, I keep the interface minimal from the very first version and separate method names instead of overloading: changing it later is much cheaper.
Sign up to mark studied questions and save your progress.