Video in progress
When designing an internal library API, do you accept the standard functional interfaces (Function, Supplier) or create your own?
For simple, generic cases, the standard interfaces: the caller can pass any lambda or method reference. When a name carries meaning in the domain, when a checked exception is needed, or when you plan to add default methods in the future, your own @FunctionalInterface. The main cost is compatibility and overload problems.
📖 Answer
The benefit of standard interfaces: the caller imports nothing, combinators like Function.andThen and Predicate.negate come ready-made, and they work with other libraries.
But when Function<Map<String, Object>, Optional<BigDecimal>> shows up in a signature, nobody knows what it is. Here a domain-named interface is better:
@FunctionalInterface
public interface PriceRule {
Optional<BigDecimal> apply(PricingContext ctx);
default PriceRule orElse(PriceRule other) {
return ctx -> apply(ctx).or(() -> other.apply(ctx));
}
}
Now the API documents itself, you can add domain combinators like orElse, and "Find usages" works in the IDE.
Other cases where you need your own interface:
- a checked exception:
interface SqlCallback<T> { T run(Connection c) throws SQLException; }: Spring'sJdbcTemplatecallbacks are exactly this; - primitive combinations missing from the JDK (
ObjLongConsumerexists, but not all of them); - if serialization is required.
The place to be careful is overloads. When two methods with the same name accept two different functional interfaces:
void submit(Runnable task);
<T> Future<T> submit(Callable<T> task);
Which one submit(() -> doWork()) picks depends on the return type of doWork and is unclear to the reader. With a lambda that throws an exception, it's different again. In a library API I avoid such overloads and separate the names: run(...), call(...).
Binary compatibility: you can't add a new abstract method to a public functional interface, because every lambda breaks. Only default methods. That's why I keep a library interface minimal from the very first version.
Sign up to mark studied questions and save your progress.