    <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  :: A Class What I Wrote</title>
        <link>https://members.accu.org/index.php/journals/2332</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>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">CVu Journal Vol 28, #6 - January 2017 + Programming Topics</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/journals/">All</a>

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

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c369/">286</a>
                    (10)
<br />

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

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

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

                                            <a href="https://members.accu.org/index.php/journals/c369-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c369+65/">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;A Class What I Wrote</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 05 January 2017 21:16:51 +00:00 or Thu, 05 January 2017 21:16:51 +00:00</p>
<p><strong>Summary:</strong>&nbsp;Paul Grenyer reduces the boilerplate with simple abstraction.</p>
<p><strong>Body:</strong>&nbsp;<p>When I was a member of ACCU, their regular publications always appealed for people to write articles for them. There were a few suggested topics, but the one which stuck in my mind was to write about a class youâ€™d written. I often used to wonder about doing this, but itâ€™s quite difficult as I rarely wrote a class which was stand alone enough to write about, without having to write about a load of other classes too. Maybe thatâ€™s a symptom of a design which is not loosely coupled, but Iâ€™ll leave that for a late night discussion with Kevlin Henney.</p>

<p>Today I wrote such a class, and was very pleased with it as it reduced a lot code which was repeated in a number of methods down to a single line of code â€“ it even manages a resource! The code I started with is in Listing 1.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
try
{
  final OutputStream os =
    response.getOutputStream();
  try
  {
    IOUtils.write(JsonTools.toJson(...), os,
      &quot;UTF-8&quot;);        
    response.flushBuffer();
  }
  finally
  {
    os.close();
  }
}
catch (IOException e) 
{
  log.warn(e);
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<p>Itâ€™s Java. It gets an output stream from a <code>HttpServletResponse</code> instance passed into a Spring MVC controller method, writes some JSON to it, flushes the buffer and cleans up. If thereâ€™s an error and an exception is thrown, the output stream is still cleaned up, the exception is handled and logged. All reasonably simple and straightforward.</p>

<p>With the class that I wrote, itâ€™s reduced to:</p>

<pre class="programlisting">
  try
  {
    new ServletResponseWriter(response)
       .write(JsonTools.toJson(...));
  }
  catch (ServletResponseWriterException e) 
  {
    log.warn(e);
  }</pre>
  
<p>An instance of the class is initialised with the <code>HttpServletResponse</code> instance and a single method called to write the JSON to the output stream. If an error occurs and an exception is thrown, itâ€™s handled and logged, just as before.</p>

<p>There is far less code to maintain by using the class instead of repeating the original code.</p>

<p>Letâ€™s take a look at the class itself, <code>ServletResponseWriter</code> in Listing 2.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
public class ServletResponseWriter
{
  private static final String UTF8 = &quot;UTF-8&quot;;

  private final ServletResponse response;

  public ServletResponseWriter
    (ServletResponse response)
  {
    this.response = response;
  }

  public void write(String data)
  {
    write(data, UTF8);
  }

  public void write(String data, String encoding)
  {
    try
    {
      final OutputStream os =
        response.getOutputStream();
      try
      {
             IOUtils.write(data, os, encoding);                
        response.flushBuffer();
      }
      finally
      {
        os.close();
      }
    }
    catch (IOException e) 
    {
      throw new ServletResponseWriterException
      (e.getMessage(), e);
   }
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<p>Letâ€™s start at the top and work our way down. The constructor takes a <code>ServletResponse</code>, which is an interface implemented by <code>HttpServletResponse</code> containing the <code>getOutputStream</code> method. The <code>ServletResponse</code> is saved within the class as an immutable field.</p>

<p>The first of the write overloads allows the user of the class to write to the output stream using UTF-8 without having to specify it every time. It calls the second overload with the UTF-8 encoding.</p>

<p>The second write overload is much the same as the original code. It gets an output stream from the response and writes the supplied string to it, flushes the buffer and cleans up. If thereâ€™s an error and an exception is thrown, the output stream is still cleaned up, the exception is handled, translated and re-thrown.</p>

<p>The keen-eyed among you will have noticed that there are two new classes here, not just one. Iâ€™m not a fan of Javaâ€™s checked exceptions. They make maintenance of code more laborious. So I like to catch them, as I have here, and translate them into an appropriately named runtime exception such as <code>ServletResponseWriterException</code>.</p>

<p><code>ServletResponseWriter</code> implements the finally for each release pattern of the original code and the common pattern implemented by classes such as Springâ€™s <code>JDBCTemplate</code> which wraps it in a reusable class intended to manage resources for you.</p>

<p>Resource management is vital, but the real advantage here is that the code is more concise, more readable and reusable. And, Iâ€™ve had the chance to write about a class I once wrote.</p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
