Java and Immutability: Creating a Simple Builder

The more I look back on what I learned about programming in school (junior high, high school, college, etc.) I realize that although it made a great base on which to learn, it really does not get you ready for problems you’re going to see in the real world.  Of course, even then the problems are always changing and what you thought was the best approach a year ago, a month ago, or even within the last hour, isn’t.

One of the largest hurdles to jump over (besides recursiveness), in my opinion, is mutable versus immutable.  The main reason is because you’re taught from the time you start programming through college (ignoring those of you who took a Haskell class) you’re only taught using C, C++, or Java.  All languages that are mutable state programming languages (yes, you can apply immutability to them and I’m getting to that) and although (perhaps) easier to learn can lead to some hard problems down the line when you have to start thinking about scalability and parallelism.  Josh Bloch, of Effective Java fame, has said that unless you have a really good reason to make a mutable class, you shouldn’t.  And if you have to make a mutable class, limit the scope of it’s mutability.

Now, as the title of the post implies, I’m going to talk about how to make immutable objects in Java and touch on some of the issues that you might run into along with how to make a builder class to instantiate this new immutable object.  There are a few conventions that you apply to an object that will normally make it immutable with a few small exceptions.

  • make the class final
  • make all fields final and private
  • if a field is mutable make a defensive copy on a get
  • only set the fields in the constructor
  • do not allow setter methods

Now, these steps will get you there but, there are a few gotchas that people normally don’t think about.  For instance, most classes with the Iterable interface or an interface that allows removal from a set or list even if it is defined as final in the class if you pass it out to the caller using this pattern:

public Iterable<SomeType> getSomething() {
  return this.myIterableSomething;
}

are in for a big surprise (unless you’re using an immutable list) because the caller can then use the remove() method on that Iterable list that you returned.

Now that you’ve got this wonderful (and hopefully) immutable class, another awesome thing you can do is make a builder class to help construct the object.  This is especially helpful if your class takes a large number of inputs into the constructor.  There are many ways to make builder classes but I’m going to demonstrate my favorite one: a static class inside of the class you want to create.

Creating the builder is really very simple.  First, have a class you want to make a builder for, in this case, let’s use SimpleClass.

final public class SimpleClass {
  private final int a;
  private final int b;

  public SimpleClass(int a, int b) {
    this.a = a;
    this.b = b;
  }

  public int getA() { return this.a; }
  public int getB() { return this.b; }
}

Now, lets create the builder class inside of the SimpleClass, like this:

final public class SimpleClass {
  .. snip ..

  public static class Builder {
    private int a;
    private int b;

    public Builder() {
      //assign some default values...
      this.a = 0;
      this.b = 0;
    }

    public Builder setA(int a) { 
      this.a = a;
      return this;
    }

    public Builder setB(int b) {
      this.b = b;
      return this;
    }

    public SimpleClass build() { return new SimpleClass(this.a, this.b); }
  }
}

With this, we now have a very barebones builder class for SimpleClass.  In practice you’d take values that absolutely have to be set in the builder’s constructor and set reasonable defaults for the optional values.  You’d then use the set* methods to set the optional values for the class.  Additionally, if you only want the user to construct objects through the builder class you can set the constructor on the class to private, leaving you with a SimpleClass listing:

final public class SimpleClass {
  private final int a;
  private final int b;

  private SimpleClass(int a, int b) {
    this.a = a;
    this.b = b;
  }

  public int getA() { return this.a; }
  public int getB() { return this.b; }

  public static class Builder {
    private int a;
    private int b;

    public Builder() {
      //assign some default values...
      this.a = 0;
      this.b = 0;
    }

    public Builder setA(int a) { 
      this.a = a;
      return this;
    }

    public Builder setB(int b) {
      this.b = b;
      return this;
    }

    public SimpleClass build() { return new SimpleClass(this.a, this.b); }
  }
}

To actually instantiate this class in practice you’d make a call like this in your code:

  SimpleClass mySimpleClass = new SimpleClass.Builder().setA(10).setB(11).build();

And, whala! You’ve created an immutable class using a builder!

With this, you’ve taken the first step toward better coding in the real world and on problems that have you dealing with scale and parallelism.  I’ll hopefully write about scale and parallelism in later posts, so stay tuned, and if you have anything you think I should write about or a place where I’ve screwed up, let me know in the comments below! 🙂

If you’d like this source code in a nice form, check it out on GitHub.

Leave a Reply

Your email address will not be published. Required fields are marked *