Skip to main content

A class what I wrote

When I was a member of the 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.

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! Here's the code I started with:


try
{
    final OutputStream os = response.getOutputStream();

    try
    {
        IOUtils.write(JsonTools.toJson(...), os, "UTF-8");        
        response.flushBuffer();
    }
    finally
    {
        os.close();
    }
}
catch (IOException e) 
{
    log.warn(e);
}  

It's Java. It gets an output stream from a HttpServletResponse 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.

With the class that I wrote, it's reduced to:

try
{
    new ServletResponseWriter(response).write(JsonTools.toJson(...));
}
catch (ServletResponseWriterException e) 
{
    log.warn(e);
}

An instance of the class is initialised with the HttpServletResponse 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.

There is far less code to maintain by using the class instead of repeating the original code.

Let's take a look at the class itself, ServletReponseWriter:

public class ServletResponseWriter
{
    private static final String UTF8 = "UTF-8";
    
    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);
        }
    }
}

Let's start at the top and work our way down. The constructor takes a ServletResponse which is an interface implemented by HttpServletResponse containing the getOutputStream method. The ServletResponse is saved within the class as an immutable field.

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.

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.

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 ServletResponseWriterException.

ServletResponseWriter implements the finally for each release pattern of the original code and the common pattern implemented by classes such as Spring's JDBCTemplate which wraps it in a reusable class intended to manage resources for you.

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.



Comments

Popular posts from this blog

Write Your Own Load Balancer: A worked Example

I was out walking with a techie friend of mine I’d not seen for a while and he asked me if I’d written anything recently. I hadn’t, other than an article on data sharing a few months before and I realised I was missing it. Well, not the writing itself, but the end result. In the last few weeks, another friend of mine, John Cricket , has been setting weekly code challenges via linkedin and his new website, https://codingchallenges.fyi/ . They were all quite interesting, but one in particular on writing load balancers appealed, so I thought I’d kill two birds with one stone and write up a worked example. You’ll find my worked example below. The challenge itself is italics and voice is that of John Crickets. The Coding Challenge https://codingchallenges.fyi/challenges/challenge-load-balancer/ Write Your Own Load Balancer This challenge is to build your own application layer load balancer. A load balancer sits in front of a group of servers and routes client requests across all of the serv...

Catalina-Ant for Tomcat 7

I recently upgraded from Tomcat 6 to Tomcat 7 and all of my Ant deployment scripts stopped working. I eventually worked out why and made the necessary changes, but there doesn’t seem to be a complete description of how to use Catalina-Ant for Tomcat 7 on the web so I thought I'd write one. To start with, make sure Tomcat manager is configured for use by Catalina-Ant. Make sure that manager-script is included in the roles for one of the users in TOMCAT_HOME/conf/tomcat-users.xml . For example: <tomcat-users> <user name="admin" password="s3cr£t" roles="manager-gui, manager-script "/> </tomcat-users> Catalina-Ant for Tomcat 6 was encapsulated within a single JAR file. Catalina-Ant for Tomcat 7 requires four JAR files. One from TOMCAT_HOME/bin : tomcat-juli.jar and three from TOMCAT_HOME/lib: catalina-ant.jar tomcat-coyote.jar tomcat-util.jar There are at least three ways of making the JARs available to Ant: Copy the JARs into th...

RESTful Behaviour Guide

I’ve used a lot of existing Representational State Transfer (REST) APIs and have created several of my own. I see a lot of inconsistency, not just between REST APIs but often within a single REST API. I think most developers understand, at a high level, what a REST API is for and how it should work, but lack a detailed understanding. I think the first thing they forget to consider is that REST APIs allow you to identify and manipulate resources on the web. Here I want to look briefly at what a REST API is and offer some advice on how to structure one, how it should behave and what should be considered when building it. I know this isn’t emacs vs vi, but it can be quite contentious. So, as  Barbossa from Pirates of the Caribbean said, this “...is more what you’d call ‘guidelines’ than actual rules.” Resources & Identifiers In their book, Rest in Practice - Hypermedia and Systems Architecture (‎ISBN: 978-0596805821), Jim Webber, Savas Parastatidis and Ian Robinson describe resour...