Generics: Duping your inner compiler

2008-06-25

Maybe I’m slow, but I recently figured out a handy use for Generics:

    public static S3Service connectS3(String id, String key) {
        AWSCredentials creds = new AWSCredentials(id, key);
        try {
            return new RestS3Service(creds);
        } catch (S3ServiceException e) {
            return failConnect(id, e);
        }
    }

where failConnect is:

    private static <T> T failConnect(String id, Exception e) {
        throw new AWSException("Unable to connect " + id + " @ Amazon!", e);
    }

It feels like being a knowledgeable (runtime) adult, duping an ignorant (compile-time) child. The child is happy, because the connect method has its returns in place, and the failConnect method obviously returns the right type. So I can reuse it here:

    public static SimpleDB connectSDB(String id, String key) {
        try {
            return new SimpleDB(id, key);
        } catch (Exception e) {
            return failConnect(id, e);
        }
    }

failConnect can obviously “return” anything. And it does! Right? Ah, kids are such dupes.

Advertisements

2 Responses to “Generics: Duping your inner compiler”

  1. Kjetil Says:

    Another solution is simply to have failConnect return the exception and have the catch block throw it. A tiny bit clearer, perhaps, though not quite as neat.

  2. Kjetil V. Says:

    That works too, although both approaches may look a little weird to inexperienced Java developers. Generally, I prefer to throw the exception at the point where it’s created. I find the stacktrace gets slightly harder to interpret if I don’t.

    When delegating the exception handling to a dedicated “fail” method, the stacktrace also becomes slightly more confusing than the common case, which is to create and throw the exception at the point of failure. But it does seem to be more common than separating the creating from the throwing, and sooner or later you get some failure handling logic that you don’t want to duplicate.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: