Often resources need to be closed after handling them. Not doing so will lead 
to leaks sooner or later tearing down the application.

It can be observed that handling resources correctly tends to be error-prone. 
This is due to the pattern commonly used in Java which involves a lot of 
boilerplate.

final InputStream in = getStream();
try {
        // deal with in
} finally {
        try {
                in.close();
        } catch (IOException ignore) {
        }
}


A better solution is to close Closeables in a helper method that swallows the 
excpetion.

final InputStream in = getStream();
try {
        // deal with in
} finally {
        IoSupport.closeQuietly(in);
}


Looks better but is not ideal either since normally you want to consume the 
stream and produce an output. This may look something like this:

final InputStream in = getStream();
String result = null;
try {
        // deal with in
        result = ...
} finally {
        IoSupport.closeQuietly(in);
}
useResult(result)


That's a real anti-pattern. It's not obvious what the code does, especially if 
the "deal with in" part gets bigger. 

Higher-order functions to the rescue! 

final String result = withResource(getStream(), new Function<InputStream, 
String>() {
        @Override public String apply(InputStream in) {
                return "read";
        }
};
useResult(result);

Nice, clear and safe. Take a stream, produce a result and close everything 
properly.

If you name the handler function (e.g. consumeStream) it it gets even better. 
You can reuse your function and the code gets very concise.

useResult(withResource(getStream(), consumeStream))

Find withResource(..) and withFile(..) (a specialized version for files that 
saves you even more typing!) in org.opencastproject.util.IoSupport. 
Accompanying tests and usage examples are in 
org.opencastproject.util.IoSupportTest (module matterhorn-common)

I'd like to encourage you to use these methods and to create likewise functions 
whenever you encounter similar problems.

Enjoy,
Christoph


_______________________________________________
Matterhorn mailing list
[email protected]
http://lists.opencastproject.org/mailman/listinfo/matterhorn


To unsubscribe please email
[email protected]
_______________________________________________

Reply via email to