I am currently implementing a fun project involving lambdas and this project makes heavy use of the ability of Java 8 to have default methods in interfaces.
But when does such "heavy use" turn into an outright abuse? Here is one example of an interface which I have defined, and its 4 methods may extend to even more in the future; am I overdoing it?
@FunctionalInterface
public interface ThrowingFunction<T, R>
extends Function<T, R>
{
R doApply(T t)
throws Throwable;
@Override
default R apply(T t)
{
try {
return doApply(t);
} catch (Error | RuntimeException e) {
throw e;
} catch (Throwable tooBad) {
throw new ThrownByLambdaException(tooBad);
}
}
default Function<T, R> orReturn(R defaultValue)
{
return t -> {
try {
return doApply(t);
} catch (Error | RuntimeException e) {
throw e;
} catch (Throwable ignored) {
return defaultValue;
}
};
}
default <E extends RuntimeException> Function<T, R> orThrow(
Class<E> exceptionClass)
{
return t -> {
try {
return doApply(t);
} catch (Error | RuntimeException e) {
throw e;
} catch (Throwable tooBad) {
throw ThrowablesFactory.INSTANCE.get(exceptionClass, tooBad);
}
};
}
}
(Not that this is relevant, but the source for ThrowablesFactory
can be viewed here.)