Builder pattern – a handy option

One of my favorite design patterns in Java is using the Builder Pattern in my DTOs (Data Transfer Objects).

Here we’re talking about POJOs (Plain Old Java Objects) whose main purpose is to transfer data.  They’re essentially a group of fields and getter/setters, and in web programming, they come into play frequently.   The Builder Pattern is appropriately used in many scenarios beyond this, but this is where I use it the most since it’s so easy and I enjoy the difference it makes in using these guys later.

Typical Standard POJO

Say we need a class to represent some data points on a monthly basis:

class MonthlyData {

    private String date;
    private double revenue;
    private double costs;

    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }

    public double getRevenue() {
        return revenue;
    }
    public void setRevenue(double revenue) {
        this.revenue = revenue;
    }

    public double getCosts() {
        return costs;
    }
    public void setCosts(double costs) {
        this.costs = costs;
    }
}

This is the standard Java- private fields with public accessors/mutators.  To create a new element we do:

    MonthlyData data = new MonthlyData();
    data.setCosts(1.02);
    data.setRevenue(12.45);
    data.setDate("2014-04-01");

Introducing the Builder Pattern

Nothing wrong with this, but if we update our setters in the Java class definition to return the class itself instead of a void, we gain the option of using another way.

With the builder pattern.  Note the only change is to the return type of the ‘setter methods’ and then return this.

class MonthlyData {

    private String date;
    private double revenue;
    private double costs;

    public String getDate() {
        return date;
    }
    public MonthlyData setDate(String date) {
        this.date = date;
        return this;
    }

    public double getRevenue() {
        return revenue;
    }
    public MonthlyData setRevenue(double revenue) {
        this.revenue = revenue;
        return this;
    }

    public double getCosts() {
        return costs;
    }
    public MonthlyData setCosts(double costs) {
        this.costs = costs;
        return this;
    }
}

Now with this one change in place, we can construct a new MonthlyData object using the same code as earlier, or we can chain the calls on the same line:

  new MonthlyData().setRevenue(12.7).setDate("2014-04-01");

While this features multiple method calls on the same line (which some people argue against), it’s effectively no different than if we created a constructor to the class taking these same parameters as arguments.   However, unlike an overloaded constructor, we don’t have to define bunch of constructors deciding in advance whether a field should be optional or not.  We’re just using the same get/set methods we’d have to write anyway.

Like I said, this is especially handy for DTO-type classes, particularly those with optional fields, and to ease testing.

More Advanced Use

Here’s a Java class I use frequently to return a single value serialized to JSON (using Jackson) from a REST service:

public class ValueDto<T> implements Serializable {
    private T value;

    public T getValue() {
        return value;
    }

    public ValueDto<T> setValue(T value) {
        this.value = value;
        return this;
    }
}

Then in any REST service where I just want to return a single value as JSON, I can do:

    return new ValueDto<Long>().setValue(1234L);

which ends up getting serialized as:

{
  "value":1234
}

And thanks to the Java generics, can also be used with Strings:

    return new ValueDto<String>().setValue("Andrew");

If you want to get real fancy, the same Builder Pattern is also a basic building block for crafting fluent APIs.  Here we can look at how Mockito uses it for setting behavior on mocks:

    when(mock.getBar().getName()).thenReturn("deep");

It’s the same pattern at in use-  each of those methods are returning the object being modified, but in such a way as to make the code extremely readable.

Takeaways

The great things about this pattern is it’s relatively free to implement– instead of a void type, return the appropriate object.  For classes used frequently, especially with optional fields and those re-used in tests, it can make a big difference later.

Leave a comment