Video in progress
When designing the public API of an internal Java library used by many teams, which OOP decisions cause the most pain later?
Open, non-final classes (users inherit and bind to internal behavior), mutable return types, exposing implementation types in signatures, and leaking transitive dependencies into the API. These later turn into a contract you can't fix.
📖 Answer
The decisions that have hurt the most in practice:
Classes open for inheritance. Someone does extends on public class HttpRetrier and overrides a protected method. In the next version you change the internal sequence of calls and their code breaks silently. The rule: a class is either designed and documented for inheritance (including which method calls which), or it's final. If you need extension, use a small interface (a strategy, a callback).
Implementation types in the signature. ArrayList<Item> getItems(), HashMap<...> config(): later you can't move to List.of() or another structure. Always use the most general interface in a signature.
Transitive dependencies in the API. If a method returns com.fasterxml.jackson.databind.JsonNode or okhttp3.Response, all users are locked to your Jackson/OkHttp version. If they use a different version, you get a classpath conflict. Return your own types.
Mutable configuration objects. client.getConfig().setTimeout(...): at runtime one thread changes it and another sees a half-changed state. An immutable config and a builder are better.
Checked exceptions. They force every caller into try/catch, and then adding a new checked exception breaks source compatibility.
On the process side:
- split the API and the implementation into separate modules (
lib-api,lib-core); - put
japicmp/revapiin CI; - for every major release, write a "what changed and how to migrate" document;
- call the first version "beta" and try it with a few internal users: the real usage patterns only show up that way.
Even for an internal library, once the number of users reaches dozens of services it becomes as expensive as an external one: every breaking change eats into the sprints of dozens of teams.
Sign up to mark studied questions and save your progress.