2010-02-17

Stream close template.

I wanted to DRY my Java code by introducing common code for patterns like this:
InputStream input = new FileInputStream(file);
try {
  doSomethingWithStream(input);
} finally {
  if (null != input) input.close();
}
So I had two approaches to try out both having two functions: one for opening stream, other for doing actual work. First solution was with template utility function that accepts 2 function-like objects, second one used template class.

Code for first approach looks like following:
interface Ctor {
  A get();
}
interface F {
  void put(A arg);
}

class Utils {
  static  void withCloseable(Ctor streamConstructor, F block) throws IOException {
    C c = null;
    try {
      c = streamConstructor.get();
      block.put(c);
    } finally {
      if (c != null)
        c.close();
    }
  }
Use case might look like this:
Utils.withCloseable(
  new Ctor() {
    InputStram get() { 
      return new FileInputStream(file);
    }
  }, 
  new F(InputStream in) {
      doSomethingWithStream(in); // Whatever
  }
);
Second approach that uses template class expects used to extend class to provie necessary methods:
abstract class WithCloseable {
  protected abstract C open() throws IOException;
  protected abstract void runWith(C c) throws IOException;

  public T exec() throws IOException {
    C c = null;
    try {
      c = open();
      runWith(c);
    } finally {
      if (c != null)
        c.close();
    }
  }
} 


Alas, while both approaches allow to make closing streams more regular they also made the code look involved and bloated. The situation only worsened when I tried to modify the code to it returns value from function that works with stream or try to nest several templates if I want to work with more than stream (for example, one for input other for output).


It is frustrating to watch every time how Java resist being more consice. I am looking forward for using Clojure or Scala in projects at my job I have no doubt that clojures if they ever appear in Java will be yet another half-solution made with compatibility as sole requirement (first one was generics).

No comments:

Post a Comment

On security

My VPS recently got banned for spam which surprised me since none of my soft there sending email. So my first thoughts were that this is a...