Methods to get single and multiple JDBC results I have two methods which are very similar apart from the method call inside and the return type. I wondered if there was a way to make it neater, i.e not duplicate the boiler plate connection code. I considered putting a flag in the method signature to switch, something like isMultiple but in the end I didn't like this and as the return type is different that won't work. I wondered if there was something nice I could do with Java 8.

Methods:

protected String getSingleFilePathResult(Query query) throws UwsException {
      JdbcPooledConnection conn = createConnection();
      try {
         return conn.getSingleFilePathResult(query);
      } catch (SQLException sqle) {
         throw new UwsException(SQL_EXCEPTION + sqle.getMessage(), sqle);
      } finally {
         closeConnection(conn);
      }
   }

protected List&lt;String&gt; getMultipleFilePathResults(Query query) throws UwsException {
      JdbcPooledConnection conn = createConnection();
      try {
         return conn.getMultipleFilePathResults(query);
      } catch (SQLException sqle) {
         throw new UwsException(SQL_EXCEPTION + sqle.getMessage(), sqle);
      } finally {
         closeConnection(conn);
      }
   }
You can factor out the boilerplate like so:

protected String getSingleFilePathResult(Query query) throws UwsException {
    return doWithConnection(conn -&gt; conn.getSingleFilePathResult(query));
}

protected List&lt;String&gt; getMultipleFilePathResults(Query query) throws UwsException {
    return doWithConnection(conn -&gt; conn.getMultipleFilePathResults(query));
}


protected &lt;T&gt; T doWithConnection(Function&lt;conn, T&gt; callback) throws UwsException {
    try (JdbcPooledConnection conn = createConnection()){
        return callback.Invoke(conn);
    } catch (SQLException sqle) {
        throw new UwsException(SQL_EXCEPTION + sqle.getMessage(), sqle);
    }
}