I recently had a discussion in the forum of an API, because they changed an exception from checked to unchecked. I believed it needs to be checked, because it is recoverable. The arguments of "the other side" were verbosity and tediousness of try/catch or throws.
If it were purely theoretical question, I'd be right, but I agree that in practice it is sometimes tedious to write all these try/catches just for the sake of rethrowing unchecked exceptions, or logging.
So, an idea came to my mind, and I wonder whether it's viable. I'll illustrate with simple code:
public interface Foo {
String foo() throws Exception;
}
public interface EasyFoo extends Foo {
String foo();
}
These are two interfaces that define the same method (and this is enforced by inheritance), but the "easy" version does not define throwing checked exceptions. Then come 2 default implementations:
public class FooImpl implements Foo {
@Override
public String foo() throws Exception {
return "foo";
}
}
public class EasyFooImpl implements EasyFoo {
Foo foo;
public EasyFooImpl(Foo foo) {
this.foo = foo;
}
@Override
public String foo() {
try {
return foo.foo();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
The latter delegates to the former, wrapping all exceptions in runtime exceptions.
And finally a factory:
public class FooFactory {
public static Foo createFoo() {
return new FooImpl();
}
public static EasyFoo createEasyFoo() {
return new EasyFooImpl(new FooImpl());
}
}
The benefits:
- the user of the API can choose how he likes to use the implementation. If he doesn't intend to do anything with the checked exceptions, he can use the "easy" version
- you support only one interface. The 2nd is the same, and you'll just have to add the methods that you have in the main one.
the user can use the
EasyFoo
in places whereFoo
is required:EasyFoo foo = FooFactory.createEasyFoo(); helper.doSomething(foo); // which is public void doSomething(Foo foo);
Enough foos - the question is, is this a viable solution that can reduce verbosity while retaining the good sides of checked exceptions?