    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Boiler Plating Database Resource Cleanup (Part 2)</title>
        <link>https://members.accu.org/index.php/articles/1563</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #91 - June 2009</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c253/">91</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-253/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+253/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Boiler Plating Database Resource Cleanup (Part 2)</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 10 June 2009 09:54:00 +01:00 or Wed, 10 June 2009 09:54:00 +01:00</p>
<p><strong>Summary:</strong>&nbsp;Timely disposal of resources is important. Paul Grenyer applies this to database access in Java.</p>
<p><strong>Body:</strong>&nbsp;<p>In my recent CVu 
				      [<a href="#CVu">CVu</a>]
				 article, 'Boiler Plating Database Resource Cleanup - Part I' 
				      [<a href="#PartI">PartI</a>]
				 I explained that cleaning up after querying a database in Java is unnecessarily verbose and complex and demonstrated how boiler plate code could be developed to reduce the amount of client code needed using the Finally For Each Release pattern 
				      [<a href="#AToTP">AToTP</a>]
				. In this article I am going to look at an alternative boiler plate solution using the Execute Around Method (EAM) 
				      [<a href="#AToTP">AToTP</a>]
				 pattern. But first, let's take another brief look at the problem.
  </p><h2>
    The problem - revisited
  </h2><p> 
    The problem is simple. Cleaning up after querying a database in Java is unnecessarily verbose and complex. Plain and simple.  Listing 1 is the code needed to lookup a single string in a database.
  </p><p> 
<table class="sidebartable"><tr><td><pre class="programlisting">
    try  
      {  
        Class.forName(driver);  
        Connection con = DriverManager.getConnection(  
           connectionString, username, password );  
        try   
        {  
          PreparedStatement ps =  
             con.prepareStatement(  
             &quot;select url from services where name =  
             'Instruments'&quot;);  
          try   
          {  
            ResultSet rs = ps.executeQuery();  
            if(rs.next())  
            {  
              System.out.println(rs.getString(&quot;url&quot;));  
            }  
            try   
            {  
              rs.close();  
            }  
            catch(SQLException e)   
            {  
              e.printStackTrace();  
            }  
          }  
          finally   
          {  
            try   
            {  
              ps.close();  
            }  
            catch(SQLException e)   
            {  
              e.printStackTrace();  
            }  
          }  
        }  
        finally   
        {  
          try   
          {  
            con.close();  
          }  
          catch(SQLException e)   
          {  
            e.printStackTrace();  
          }  
        }  
      }  
      catch(Exception e)  
      {  
        e.printStackTrace();  
      }  
</pre>
</td></tr><tr><td class="title">Listing 1</td></tr></table>
  </p>
<p> 
    This is a lot of code to get one string out of a database and most of it must be repeated every time a database is accessed. Most of it is error handling and resource management. For a more detailed look at this code see Part I.
  </p><h2>
    Execute Around Method
  </h2><p> 
    The EAM pattern is described by Kevlin Henney in his article 'Another Tale of Two Patterns'. EAM describes how to '<span class="quote">encapsulate pairs of actions in the object that requires them, not code that uses the object, and pass usage code to the object as another object</span>'.
  </p><p> 
    The advantage of EAM over Finally For Each Release is that the client is able to use a resource simply by implementing an interface, using the resource passed to the subclass without worrying about how to clean up and then simply pass an instance of the subclass to another object for resource acquisition, execution and cleanup.
  </p><h2>
    To check or not to check
  </h2><p> 
    Checked <tt class="code">Exception</tt>s 
				      [<a href="#CheckedExceptions">CheckedExceptions</a>]
				 in Java have their advantages and disadvantages and are a source of much controversy. In my previous article I made all of my interface methods throw <tt class="code">Exception</tt> (except for <tt class="code">ConnectionPolicy</tt>, which throws its own custom exception) so that client code can throw almost any exception type it likes. This effectively negates the checked part of checked exceptions. 
  </p><p> 
    Instead of using checked exceptions for the EAM design, I am forcing client code to catch and deal with checked exceptions or translate and rethrow them as runtime exceptions, by omitting any exception specification from interface method signatures.
  </p><p> 
    To aid with this I have written an <tt class="code">ErrorPolicy</tt> interface (Listing 2)and a <tt class="code">DefaultErrorPolicy</tt> class (Listing 3) that translate <tt class="code">Exception</tt> into <tt class="code">RuntimeException</tt> where appropriate.
  </p><p> 
<table class="sidebartable"><tr><td><pre class="programlisting">
    public interface ErrorPolicy   
    {  
      void handleError(Exception ex);  
      void handleCleanupError(Exception ex);  
    }
</pre>
</td></tr><tr><td class="title">Listing 2</td></tr></table>
  </p>
  <p> 
<table class="sidebartable"><tr><td><pre class="programlisting">
    public class DefaultErrorPolicy  
       implements ErrorPolicy   
    {  
      private Exception firstException = null;  
      @Override  
      public void handleCleanupError(Exception ex)   
      {  
        handleError(ex);  
      }  
      @Override  
      public void handleError(Exception ex)   
      {  
        if (firstException == null)  
        {  
          firstException = ex;  
          throw new RuntimeException(ex);  
        }  
      }  
    }  
</pre>
</td></tr><tr><td class="title">Listing 3</td></tr></table>
  </p>
<p> 
    The <tt class="code">ErrorPolicy</tt> interface is designed to allow exceptions thrown as a result of an error from using a database resource to be handled differently to those thrown as a result of cleaning up a database resource. For example, a user may want to rethrow only use exceptions and simply log or ignore cleanup exceptions.
  </p><p> <tt class="code">DefaultErrorPolicy</tt> only rethrows the first exception it is asked to handle. This guarantees that a cleanup exception, which would generally be thrown after a use exception, does not hide the use exception. If I was including the ability to log in my design I would log all exceptions handled by <tt class="code">DefaultErrorPolicy</tt>.
  </p><p> 
    The error policy must always be set and <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">can</span> always be used in the same way. To provide the necessary consistency when setting the error policy I wrote the following interface:
  </p>
<pre class="programlisting">
      public interface ErrorPolicyUser   
      {  
        void setErrorPolicy(ErrorPolicy errorPolicy);  
      }  
</pre><p> 
    To provide a common, optional method of storing and accessing a reference to the error policy I wrote the abstract class in Listing 4.
  </p><p> 
<table class="sidebartable"><tr><td><pre class="programlisting">
    public abstract class AbstractErrorPolicyUser  
       implements ErrorPolicyUser   
    {  
      private ErrorPolicy errorPolicy =  
         new DefaultErrorPolicy();  
      protected ErrorPolicy getErrorPolicy()  
      {  
        return errorPolicy;  
      }  
      @Override  
      public void setErrorPolicy(  
         ErrorPolicy errorPolicy)   
      {  
        this.errorPolicy = errorPolicy;  
      }  
    }  
</pre>
</td></tr><tr><td class="title">Listing 4</td></tr></table>
  </p>
<h2>
    From policy to factory
  </h2><p> 
    The more I thought about and discussed the <tt class="code">ConnectionPolicy</tt> interface from my previous article, the more I felt it was more like an Abstract Factory 
				      [<a href="#GoF">GoF</a>]
				 than a policy. Therefore I have renamed it.
  </p>
<pre class="programlisting">
      public interface ConnectionFactory  
         extends ErrorPolicyUser  
      {  
        Connection connect();  
        void disconnect(Connection con);  
      }  
</pre><p> 
    I want <tt class="code">ConnectionFactory</tt> clients to be forced to accept an error policy without relying on it being passed to subclass constructors the interface has no control over. Extending the <tt class="code">ErrorPolicyUser</tt> interface also means that the error policy can be set internally by <tt class="code">ConnectionProvider</tt> (discussed next). 
  </p><p> 
    Most <tt class="code">Connection</tt> objects are cleaned up in the same way, so having the common code encapsulated in an abstract class prevents unnecessary code duplication. An abstract class is also the ideal place for boiler plate error policy handling (Listing 5).
  </p><p> 
<table class="sidebartable"><tr><td><pre class="programlisting">
    public abstract class AbstractConnectionFactory   
       extends AbstractErrorPolicyUser implements ConnectionFactory   
    {  
      @Override  
      public void disconnect(Connection con)  
      {  
        if (con != null)  
        {  
          try  
          {  
            con.close();  
          }  
          catch(final SQLException ex)  
          {  
            getErrorPolicy().handleCleanupError(ex);  
          }  
        }  
      }  
    }  
</pre>
</td></tr><tr><td class="title">Listing 5</td></tr></table>
  </p>
<p> <tt class="code">AbstractConnectionFactory</tt> is a good example of how a class that needs to implement <tt class="code">ErrorPolicyUser</tt> can extend <tt class="code">AbstractErrorPolicyUser</tt> to get the implementation and access to the error policy for free.
  </p><p> 
    The disconnect method is also a good example of how the error policy is used to translate a checked exception into something else, in this case a runtime exception. A little more thought needs to be put into the connection creation factories to make sure all exceptions are caught and passed to the error policy (Listing 6).
  </p><p> 
<table class="sidebartable"><tr><td><pre class="programlisting">
    public class StringConnection  
       extends AbstractConnectionFactory   
    {  
      ...  
      @Override  
      public Connection connect()   
      {  
        Connection con = null;  
        try  
        {  
          Class.forName(driver);  
          con = DriverManager.getConnection(  
             connectionString, username, password);  
          try  
          {  
            if (database != null)  
            {  
              con.setCatalog(database);  
            }  
          }  
          catch(SQLException ex)  
          {  
            try  
            {  
              getErrorPolicy().handleError(ex);  
            }  
            finally  
            {  
              disconnect(con);  
           }  
          }  
        }  
        catch(ClassNotFoundException ex)  
        {  
          getErrorPolicy().handleError(ex);  
        }  
        catch(SQLException ex)  
        {  
          getErrorPolicy().handleError(ex);  
        }  
        return con;  
      }  
    }  
</pre>
</td></tr><tr><td class="title">Listing 6</td></tr></table>
  </p>
<h2>
    ConnectionProvider
  </h2><p> 
    The concept of a connection provider was suggested to me by Adrian Fagg. The idea is that a single class is responsible for acquiring a connection, providing it to another class for use and releasing it again. This is Execute Around Method! 
  </p><p> 
    The advantage over <tt class="code">DbResourceHandler</tt> from my previous article is equal encapsulation while making the client less restricted by what they can do with the connection. It does, however, suffer from the same disadvantage that one method is required for uses of the connection which return values and another for uses that do not. 
  </p><p> 
    To allow for this, two connection use interfaces are required. The <tt class="code">ConnectionUser</tt> interface is for uses of the connection that do not return a value:
  </p>
<pre class="programlisting">
 
      public interface ConnectionUser   
         extends ErrorPolicyUser  
      {  
        void use(Connection con);  
      }  
</pre><p> 
    The <tt class="code">ConnectionValue</tt> interface is parameterised for the type returned from uses of the connection that return a value:
  </p>
<pre class="programlisting">
      public interface ConnectionValue&lt;T&gt;  
         extends ErrorPolicyUser   
      {  
        T fetch(Connection con);  
      }  
</pre><p> 
    The construction of the <tt class="code">ConnectionProvider</tt> class is very straight forward. The basic constructor takes a connection factory, creates a <tt class="code">DefaultErrorPolicy</tt> and passes them both to another constructor that stores the references and passes the error policy to the connection factory. This means that clients of the connection provider are free to use the default error policy or provide their own. (Listing 7)
  </p><p> 
<table class="sidebartable"><tr><td><pre class="programlisting">
    public final class ConnectionProvider   
    {  
      private final ConnectionFactory conFactory;  
      private final ErrorPolicy errorPolicy;  
      public ConnectionProvider(  
         ConnectionFactory conFactory)  
      {  
        this(conFactory, new DefaultErrorPolicy());  
      }  
      public ConnectionProvider(  
         ConnectionFactory conFactory,  
         ErrorPolicy errorPolicy)  
      {  
        this.conFactory = conFactory;  
        this.errorPolicy = errorPolicy;  
        this.conFactory.setErrorPolicy(  
           this.errorPolicy);  
      }  
      ...  
    }  
</pre>
</td></tr><tr><td class="title">Listing 7</td></tr></table>
  </p>
<p> <tt class="code">ConnectionProvider</tt> has two other methods. One that provides a connection to a <tt class="code">ConnectionUser</tt> and the other which provides a connection to a <tt class="code">ConnectionValue</tt> and returns the fetched value (Listing 8).
  </p><p> 
<table class="sidebartable"><tr><td><pre class="programlisting">
    public final class ConnectionProvider   
    {  
      ...  
      public void provideTo( ConnectionUser user )  
      {  
        user.setErrorPolicy(errorPolicy);  
        final Connection con = conFactory.connect();  
        try  
        {  
          user.use(con);  
        }  
        finally  
        {  
          conFactory.disconnect(con);  
        }  
      }  
      public &lt;T&gt; T provideTo(  
         ConnectionValue&lt;T&gt; fetcher )  
      {  
        fetcher.setErrorPolicy(errorPolicy);  
        final Connection con = conFactory.connect();  
        T result = null;  
        try  
        {  
          result = fetcher.fetch(con);  
        }  
        finally  
        {  
          conFactory.disconnect(con);  
        }  
          return result;  
      }  
    }  
</pre>
</td></tr><tr><td class="title">Listing 8</td></tr></table>
  </p>
<p> 
    Both methods pass the error policy to the user of the connection, create the connection, pass it to the user and cleanup the connection. They rely on the connection factory to deal with any errors. The example in ListingÂ 9 shows how the <tt class="code">ConnectionProvider</tt> can be used.
  </p><p> 
<table class="sidebartable"><tr><td><pre class="programlisting">
    class User extends AbstractErrorPolicyUser  
       implements ConnectionUser  
    {  
      @Override  
      public void use(Connection con)  
      {  
        // Use the connection  
      }  
    }  
    final ConnectionProvider cp =   
       new ConnectionProvider(  
       new StringConnection(...));  
    cp.provideTo( new User() );  
</pre>
</td></tr><tr><td class="title">Listing 9</td></tr></table>
  </p>
<p> 
    The <tt class="code">User</tt> class extends the <tt class="code">AbstractErrorPolicyUser</tt> to get the common error policy storage functionality and implements <tt class="code">ConnectionUser</tt> so that it can be handled by <tt class="code">ConnectionProvider</tt>. There is a single override where the connection is used. 
  </p><p> 
    Having to extend <tt class="code">AbstractErrorPolicyUser</tt><span style="  font-style: italic; font-weight: normal; vertical-align: baseline">and</span> implement <tt class="code">ConnectionUser</tt> is not ideal. My original design had an <tt class="code">AbstractConnectionUser</tt> class that extended <tt class="code">AbstractErrorPolicyUser</tt> and implemented <tt class="code">ConnectionUser</tt> so that clients only had to extend a single class. This meant having a similar abstract class for every user and value variant, which did not seem worth it when, as we will see later, the user and value variants are encapsulated in another class unless the client wants something custom.
  </p><h2>
    StatementProvider
  </h2><p> 
    The <tt class="code">StatementProvider</tt> class (Listing 10) is a natural progressions from the <tt class="code">ConnectionProvider</tt> and uses EAM in the same way to provide a <tt class="code">Statement</tt> to a client without the client needing to worry about acquisition or cleanup.
  </p><p> 
<table class="sidebartable"><tr><td><pre class="programlisting">
    public final class StatementProvider   
    {  
      private final Connection con;  
      private final ErrorPolicy errorPolicy;  
      public StatementProvider(  
         Connection con, ErrorPolicy errorPolicy)  
      {  
        this.con = con;  
        this.errorPolicy = errorPolicy;  
      }  
      public void provideTo( StatementUser user )  
      {  
        user.setErrorPolicy(errorPolicy);  
        try  
        {  
          final Statement stmt =  
             con.createStatement();  
          try  
          {  
            user.use(stmt);  
          }  
          finally  
          {  
            try  
            {  
              stmt.close();  
            }  
            catch(SQLException ex)  
            {  
              errorPolicy.handleCleanupError(ex);  
            }  
          }  
        }  
        catch(SQLException ex)  
        {  
          errorPolicy.handleError(ex);  
        }  
      }  
      public &lt;T&gt; T provideTo(  
         StatementValue&lt;T&gt; fetcher )  
      {  
        fetcher.setErrorPolicy(errorPolicy);  
        T result = null;  
        try  
        {  
          final Statement stmt =  
             con.createStatement();  
          try  
          {  
            result = fetcher.use(stmt);  
          }  
          finally  
          {  
            try  
            {  
              stmt.close();  
            }  
            catch(SQLException ex)  
            {  
              errorPolicy.handleCleanupError(ex);  
            }  
          }  
        }  
        catch(SQLException ex)  
        {  
          errorPolicy.handleError(ex);  
        }  
        return result;  
      }  
    }  
</pre>
</td></tr><tr><td class="title">Listing 10</td></tr></table>
  </p>
<p> 
    The construction is simple and takes only a <tt class="code">Connection</tt>, from which to create the statement, and an error policy. Again, it has two <tt class="code">provideTo</tt> methods. One paramatised method that passes the <tt class="code">Statement</tt> to a <tt class="code">StatementValue</tt>:
  </p>
<pre class="programlisting">
      public interface StatementValue&lt;T&gt;  
         extends ErrorPolicyUser  
      {  
        T use(Statement stmt);  
      }  
</pre><p> 
    and returns a value. The other method passes the <tt class="code">Statement</tt> to a <tt class="code">StatementUser</tt>:
  </p>
<pre class="programlisting">
      public interface StatementUser  
         extends ErrorPolicyUser   
      {  
        void use(Statement stmt);  
      }  
</pre><p> 
    Both methods pass the error policy to the user of the statement, create the statement, pass it to the user, clean it up again and are responsible for error handling.
  </p><p> 
    The execution of statements that do not return a value is very straight forward, so I wrote <tt class="code">StatementUser</tt> for this purpose (Listing 11).
  </p><p> 
<table class="sidebartable"><tr><td><pre class="programlisting">
    public class Execute  
       extends AbstractErrorPolicyUser   
       implements StatementUser   
    {  
      private final String sql;  
      public Execute(String sql)  
      {  
        this.sql = sql;  
      }  
      @Override  
      public void use(Statement stmt)   
      {  
        try  
        {  
          stmt.execute(sql);  
        }  
        catch(SQLException ex)  
        {  
          getErrorPolicy().handleError(ex);  
        }  
      }  
    }  
</pre>
</td></tr><tr><td class="title">Listing 11</td></tr></table>
  </p>
<h2>
    ResultSetProvider
  </h2><p> 
    Executing statements that return one or more values is less straight forward and requires a <tt class="code">ResultSetProvider</tt> (Listing 12).
  </p><p> 
<table class="sidebartable"><tr><td><pre class="programlisting">
    public final class ResultSetProvider   
    {  
      private final String sql;  
      private final Statement stmt;  
      private final ErrorPolicy errorPolicy;	  
      public ResultSetProvider(String sql,   
         Statement stmt, ErrorPolicy errorPolicy)  
      {  
        this.sql = sql;  
        this.stmt = stmt;  
        this.errorPolicy = errorPolicy;  
      }  
 
      public &lt;T&gt; T provideTo(  
         ResultSetFunction&lt;T&gt; fetcher)  
      {  
        fetcher.setErrorPolicy(errorPolicy);  
        T result = null;  
        try  
        {  
          final ResultSet rs = stmt.executeQuery(sql);  
          try  
          {  
            result = fetcher.read(rs);  
          }  
          finally  
          {  
            try  
            {  
              rs.close();  
            }  
            catch(Exception ex)  
            {  
              errorPolicy.handleCleanupError(ex);  
            }  
          }  
        }  
        catch(SQLException ex)  
        {  
          errorPolicy.handleError(ex);  
        }  
        return result;  
      }  
    }  
</pre>
</td></tr><tr><td class="title">Listing 12</td></tr></table>
  </p>
<p> 
    Again, this is another natural progression from <tt class="code">ConnectionProvider</tt>. The <tt class="code">ResultSetProvider</tt> takes the SQL query to execute to create the result set, a <tt class="code">Statement</tt> from which to create the record set and an error policy. There is only a single paramatised <tt class="code">provideTo</tt> method as a value is always returned.
  </p><p> 
    The <tt class="code">ResultSet</tt> is provided to a  <tt class="code">ResultSetFunction</tt>:
  </p>
<pre class="programlisting">
 
      public interface ResultSetFunction&lt;T&gt;  
         extends ErrorPolicyUser  
      {  
        T read(ResultSet rs);  
      }  
 
</pre><p> 
    that is parameterised on return type. The method passes the error policy to the user, creates the <tt class="code">RecordSet</tt> from the <tt class="code">Statement</tt> and SQL query, passes the <tt class="code">ResultSet</tt> to the <tt class="code">ResultSetFunction</tt>, cleans up, handles any errors and returns the value.
  </p><p> 
    With the <tt class="code">ResultSetProvider</tt>, executing a query that returns a value is almost as simple as executing one that does not and can benefit from similar boilerplate (Listing 13).
  </p><p> 
<table class="sidebartable"><tr><td><pre class="programlisting">
    public class ExecuteQuery&lt;T&gt;  
       extends AbstractErrorPolicyUser   
       implements StatementValue&lt;T&gt;   
    {  
      private final String sql;  
      private final ResultSetFunction&lt;T&gt; rsUser;  
      public ExecuteQuery(  
         String sql, ResultSetFunction&lt;T&gt; rsUser)  
      {  
        this.rsUser = rsUser;  
        this.sql = sql;  
      }  
      @Override  
      public T use(Statement stmt)   
      {  
        return new ResultSetProvider( sql, stmt,  
           getErrorPolicy()).provideTo(rsUser);  
      }  
    }  
</pre>
</td></tr><tr><td class="title">Listing 13</td></tr></table>
  </p>
<p> 
    The <tt class="code">ExecuteQuery</tt> class is paramatised on the return type from the query. It takes a SQL query and <tt class="code">ResultSetFunction</tt> via its constructor. When an instance is passed to a <tt class="code">StatementProvider</tt><tt class="code">provideTo</tt> method it uses a <tt class="code">ResultSetProvider</tt> and the <tt class="code">ResultSetFunction</tt> to execute and return the results of the query.
  </p><h2>
    Query
  </h2><p> 
    All of this boilerplate can be wrapped in a single class that provides two static methods, one to execute methods that return a value and another for ones that do not (Listing 14).
  </p><p> 
<table class="sidebartable"><tr><td><pre class="programlisting">
    public final class Query   
    {  
      ...  
      public static void execute(  
         ConnectionProvider conProvider,  
         String sql) throws Exception  
      {  
        conProvider.provideTo(new User(sql));  
      }  
      public static &lt;T&gt; T execute(  
         ConnectionProvider conProvider,  
         String sql, ResultSetFunction&lt;T&gt; rsUser)  
         throws Exception  
        {  
          return conProvider.provideTo(  
             new Value&lt;T&gt;(sql,rsUser));  
        }  
      private Query()  
      {}  
    }  
</pre>
</td></tr><tr><td class="title">Listing 14</td></tr></table>
  </p>
<p> 
    Both methods take a <tt class="code">ConnectionProvider</tt> and a SQL query. The method which returns a value also takes a <tt class="code">ResultSetFunction</tt> to process the result set into the return value. Both methods pass an instance of a nested class to the connection provider.
  </p><p> 
    The nested class that handles queries that do not return a value is called <tt class="code">User</tt> (Listing 15).
  </p><p> 
<table class="sidebartable"><tr><td><pre class="programlisting">
    private static class User  
       extends AbstractErrorPolicyUser   
       implements ConnectionUser  
    {  
 
      private final String sql;  
      public User(String sql)  
      {  
        this.sql = sql;  
      }  
      @Override  
 
      public void use(Connection con)  
      {  
        new StatementProvider(  
           con,getErrorPolicy()).provideTo(  
           new Execute(sql) );  
      }  
    }  
</pre>
</td></tr><tr><td class="title">Listing 15</td></tr></table>
  </p>
<p> 
    It takes the SQL query via its constructor and, when passed to a <tt class="code">ConnectionProvider</tt>, uses the <tt class="code">StatementProvider</tt> and <tt class="code">Execute</tt> classes to execute the query.
  </p><p> 
    The nested class that handles queries that return a value is called <tt class="code">Value</tt> (Listing 16).
  </p><p> 
<table class="sidebartable"><tr><td><pre class="programlisting">
    private static class Value&lt;T&gt;  
       extends AbstractErrorPolicyUser   
       implements ConnectionValue&lt;T&gt;  
    {  
      private final String sql;  
      private final ResultSetFunction&lt;T&gt; rsUser;  
      public Value(String sql,  
         ResultSetFunction&lt;T&gt; rsUser)  
      {  
        this.rsUser = rsUser;  
        this.sql = sql;  
      }  
      @Override  
      public T fetch(Connection con)   
      {  
        return new StatementProvider(  
        con,getErrorPolicy()).provideTo(  
        new ExecuteQuery&lt;T&gt;(sql,rsUser) );  
      }  
    }  
</pre>
</td></tr><tr><td class="title">Listing 16</td></tr></table>
  </p>
<p> 
    It takes the SQL query and a <tt class="code">ResultSetFunction</tt> via its constructor and, when passed to a <tt class="code">ConnectionProvider</tt>, uses the <tt class="code">StatementProvider</tt> and <tt class="code">ExecuteQuery</tt> classes and the <tt class="code">ResultSetFunction</tt> interface to execute the query and return the result.
  </p><h2>
    AbstractResultSetFunction
  </h2><p> 
    The <tt class="code">ResultSetFunction</tt> interface needs a little further explanation as it is the only interface most clients will need to implement albeit then only for queries that return a value.
  </p>
<pre class="programlisting">
 
    public interface ResultSetFunction&lt;T&gt;  
       extends ErrorPolicyUser  
    {  
      T read(ResultSet rs);  
    }  
</pre><p> 
    The interface extends <tt class="code">ErrorPolicyUser</tt>, which means clients can make use of <tt class="code">AbstractErrorPolicyUser</tt> to get the common implementation. As I will demonstrate later, it will often be useful to extend <tt class="code">ResultSetFunction</tt> using an anonymous class. Anonymous classes cannot inherit from more than one class or interface, therefore I have written an AbstractResultSetFunction class that does nothing other than extend <tt class="code">AbstractErrorPolicyUser</tt> and implement <tt class="code">ResultSetFunction</tt>:
  </p>
<pre class="programlisting">
     public abstract class AbstractResultSetFunction&lt;T&gt;  
        extends AbstractErrorPolicyUser  
        implements ResultSetFunction&lt;T&gt;   
     {}  
</pre><p> 
    Now all clients have to do is extend <tt class="code">AbstractResultSetFunction</tt> and implement the read method.
  </p><p> 
    The read method takes a <tt class="code">ResultSet</tt> and returns a value. It is responsible for extracting the results from the result set and processing them into something that can be returned. As read does not have an exception specification it is also responsible for error handling. For example, retrieving a single string from a database table (Listing 17) or retrieving multiple strings from a database table (Listing 18).
  </p><p> 
<table class="sidebartable"><tr><td><pre class="programlisting">
    new AbstractResultSetFunction&lt;String&gt;()  
    {  
      @Override  
      public String read(ResultSet rs)  
      {  
        String result = null;  
        try  
        {  
          if (rs.next())  
          {  
            result = rs.getString(&quot;url&quot;);  
          }  
        }  
        catch(SQLException ex)  
        {  
          getErrorPolicy().handleError(ex);  
        }  
        return result;  
      }  
    }  
</pre>
</td></tr><tr><td class="title">Listing 17</td></tr></table>
  </p>
<p> 
<table class="sidebartable"><tr><td><pre class="programlisting">
    new AbstractResultSetFunction&lt;List&lt;String&gt;&gt;()  
    {  
      @Override  
      public List&lt;String&gt; read(ResultSet rs)  
      {  
        List&lt;String&gt; result =   
           new ArrayList&lt;String&gt;();  
        try  
        {  
          while (rs.next())  
          {  
            result.add(rs.getString(&quot;url&quot;));  
          }  
        }  
        catch(SQLException ex)  
        {  
          getErrorPolicy().handleError(ex);  
        }  
        return result;  
      }  
    }  
</pre>
</td></tr><tr><td class="title">Listing 18</td></tr></table>
  </p>
<h2>
    Putting it all together
  </h2><p> 
    To use the boilerplate to query a database, a client must first create a connection factory:
  </p>
<pre class="programlisting">
      final ConnectionFactory conFactory =  
        new StringConnection(DRIVER, CONNECTION_STRING)  
        .setUser(USERNAME, PASSWORD)  
        .setDatabase(DATABASE);  
</pre><p> 
    Then create a connection provider and pass it the connection factory and, optionally, a custom error policy:
  </p>
<pre class="programlisting">
      final ConnectionProvider cp =  
         new ConnectionProvider(conFactory);  
</pre><p> 
    Once created the connection factory and connection provider can be used for any number of queries and therefore only need to be created once. Executing a query that does not return any results can then be done with a single statement:
  </p>
<pre class="programlisting">
      Query.execute( cp,  
        &quot;insert into services ([name],[url])&quot; +    
        &quot;VALUES(  
        'Log','http://prodserv01/axis/services/Log')&quot;);  
</pre><p> 
    Queries that return results only take a little more, almost all of which is the anonymous class that processes the results from the result set (Listing 19).
  </p><p> 
<table class="sidebartable"><tr><td><pre class="programlisting">
    final String s =  
      Query.execute( cp,  
         &quot;select url from services where name =  
         'Instruments'&quot;,   
         new AbstractResultSetFunction&lt;String&gt;()  
         {  
        @Override  
        public String read(ResultSet rs)  
        {  
          String result = null;  
          try  
            {  
               if (rs.next())  
               {  
                  result = rs.getString(&quot;url&quot;);  
               }  
             }  
             catch(SQLException ex)  
             {  
               getErrorPolicy().handleError(ex);  
             }  
             return result;  
           }
     })
</pre>
</td></tr><tr><td class="title">Listing 19</td></tr></table>
  </p>
<h2>
    Conclusion
  </h2><p> 
    Boiler plating database resource cleanup with Execute Around Method offers a high level of safety and encapsulation while not compromising on control of the database resources in client code. Reducing the amount of code that has to be written each time also reduces the possibility of mistakes and resource leaks.</p><h2>
    Acknowledgements
  </h2><p> 
    Thank you to Adrian Fagg for guidance into Execute Around Method, not to mention quite a bit of help with the design.
  </p><h2>
    References
  </h2><p class="bibliomixed"><a name="AToTP"></a> 
    [AToTP] 'Another Tale of Two Patterns:' <a href="http://www.two-sdg.demon.co.uk/curbralan/papers/AnotherTaleOfTwoPatterns.pdf">http://www.two-sdg.demon.co.uk/curbralan/papers/AnotherTaleOfTwoPatterns.pdf</a>
  </p><p class="bibliomixed"><a name="CheckedExceptions"></a> 
    [CheckedExceptions] 'Checked Exceptions' <a href="http://en.wikipedia.org/wiki/Exception_handling">http://en.wikipedia.org/wiki/Exception_handling#Checked_exceptions</a>
  </p><p class="bibliomixed"><a name="CVu"></a> 
    [CVu] CVu: <a href="http://accu.org/index.php/journals/c77/">http://accu.org/index.php/journals/c77/</a>
  </p><p class="bibliomixed"><a name="GoF"></a> 
    [GoF] Gang of Four: Design Patterns : Elements of reusable object-oriented software by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides. Addison Wesley ISBN-13: 978-0201633610
  </p><p class="bibliomixed"><a name="PartI"></a> 
    [Part I]  'Boiler Plating Database Resource Cleanup' - Part I: <a href="http://www.marauder-consulting.co.uk/Boiler_Plating_Database_Resource_Cleanup_-_Part_I.pdf">http://www.marauder-consulting.co.uk/Boiler_Plating_Database_Resource_Cleanup_-_Part_I.pdf</a>
  </p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
