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

Bloodstock 2009

This year was one of the best Bloodstock s ever, which surprised me as the line up didn't look too strong. I haven't come away with a list of bands I want to buy all the albums of, but I did enjoy a lot of the performances. Insomnium[6] sound a lot like Swallow the Sun and Paradise Lost. They put on a very good show. I find a lot of old thrash bands quite boring, but Sodom[5] were quite good. They could have done with a second guitarist and the bass broke in the first song and it seemed to take ages to get it fixed. Saxon[8] gave us some some classic traditional heavy metal. Solid, as expected. The best bit was, following the guitarist standing on a monitor, Biff Bifford ripped off the sign saying "DO NOT STAND" and showed it to the audience. Once their sound was sorted, Arch Enemy[10] stole the show. They turned out not only to be the best band of the day, but of the festival, but then that's what you'd expect from Arch Enemy. Carcass[4] were very disappoin