A class what I wrote

comp

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

ServletResponseWriter:

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.

 

 

Originally published at paulgrenyer.blogspot.com

Words by Paul Grenyer

    Keep up to date by email

    Sign-up to receive regular updates on all of our content and site activities.