Video in progress
How do you design an extensible API that other teams write plugins for, so that you can change it later without breaking users?
I start with a small interface and immutable parameter objects, hide the implementation classes, and add new capabilities through default methods or new interfaces. On every release I check binary compatibility automatically (japicmp or revapi).
📖 Answer
A plugin API is the strictest contract there is: you don't see the implementations and you can't fix them.
Design rules:
- A parameter object, not a long signature.
public interface PricingPlugin {
PriceAdjustment adjust(PricingContext ctx);
}
public final class PricingContext { // not a record: adding a component breaks the constructor
public Money basePrice() { ... }
public CustomerTier tier() { ... }
// if region() is added in the next version, nobody breaks
}
Adding a new argument to a method signature breaks all plugins; adding a getter to the context object doesn't.
-
Keep the interfaces users implement very small. A new method is added only as a
default, and the default behavior is "do nothing". -
Only the API package is public. The implementation is not exported with JPMS, or it sits in an
internalpackage marked "no guarantees" in the docs. Otherwise users bind to internal classes and you can never change them. -
A discovery mechanism:
ServiceLoader, or injectingList<PricingPlugin>in Spring. A plugin should have anapiVersion()or capability methods, so the host can recognize an old plugin and adapt. -
A plugin failure must not take down the host. Wrap every call in
try/catch, a timeout and metrics; one bad plugin must not stop the whole price calculation.
Evolution:
@Deprecated(forRemoval = true)and a grace period of at least one major version;- follow semver strictly;
- in CI,
japicmpchecks binary and source compatibility against the previous release and fails the build on a break.
The biggest mistake is exposing too much in the first version. Adding later is easy, removing is almost impossible.
Sign up to mark studied questions and save your progress.