Video in progress
How reasonable is it to use default methods in interfaces for code reuse (as a mixin)?
For small, stateless helper behavior it's fine: convenience methods built on top of the interface's other abstract methods. But an interface has no state (fields), so imitating an abstract class with default methods gives a confusing, brittle design.
📖 Answer
Good use is when the interface adds convenience on top of its own abstract methods:
public interface TimeSource {
Instant now();
default boolean isExpired(Instant deadline) {
return now().isAfter(deadline);
}
default LocalDate today(ZoneId zone) {
return LocalDate.ofInstant(now(), zone);
}
}
The implementation provides only now() and the rest comes for free. The JDK does the same: Comparator.reversed(), Collection.removeIf(), Iterable.forEach().
Bad use is cramming behavior that needs state into an interface:
interface Auditable {
default void touch() {
setUpdatedAt(Instant.now()); // asks the implementation for the state
setUpdatedBy(currentUser()); // hidden global state
}
void setUpdatedAt(Instant t);
void setUpdatedBy(String u);
}
Problems:
- the interface forces the implementation to expose setters, which breaks encapsulation;
- default methods are
public(Java 9+ hasprivateinterface methods, but only as internal helpers), so everything ends up in the API; - if several "mixins" provide a default with the same name, you get a conflict and have to resolve it by hand with
X.super.m(); - you can't provide
equals,hashCodeortoStringas defaults.
For a case like this, an abstract class (for example JPA audit fields with @MappedSuperclass) or composition (an AuditInfo embeddable field) is more appropriate. The main purpose of default methods was to extend an interface without breaking existing implementations, not to simulate multiple inheritance.
Sign up to mark studied questions and save your progress.