@FreeBuilder

Automatic generation of the Builder pattern for Java 1.6+

View on GitHub
The Builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters. Effective Java, Second Edition, page 39
  1. Background
  2. How to use @FreeBuilder
    1. Quick start
    2. What you get
    3. Defaults and constraints
    4. Optional values
    5. Collections and Maps
    6. Nested buildable types
    7. Builder construction
    8. Partials
    9. IDEs
    10. GWT
  3. Alternatives
    1. AutoValue vs @FreeBuilder
    2. Proto vs @FreeBuilder
  4. Wait, why "free"?
  5. License

Background

Implementing the Builder pattern in Java is tedious, error-prone and repetitive. Who hasn't seen a ten-argument constructor, thought cross thoughts about the previous maintainers of the class, then added "just one more"? Even a simple four-field class requires 39 lines of code for the most basic builder API, or 72 lines if you don't use a utility like AutoValue to generate the value boilerplate.

@FreeBuilder produces all the boilerplate for you, as well as free extras like JavaDoc, getter methods, collections support, nested builders, and partial values (used in testing), which are highly useful, but would very rarely justify their creation and maintenance burden in hand-crafted code. (We also reserve the right to add more awesome methods in future!)

[The Builder pattern] is more verbose…so should only be used if there are enough parameters, say, four or more. But keep in mind that you may want to add parameters in the future. If you start out with constructors or static factories, and add a builder when the class evolves to the point where the number of parameters starts to get out of hand, the obsolete constructors or static factories will stick out like a sore thumb. Therefore, it's often better to start with a builder in the first place. Effective Java, Second Edition, page 39

How to use @FreeBuilder

Quick start

Add the @FreeBuilder artifact as an optional dependency to your Maven POM:

<dependencies>
  <dependency>
    <groupId>org.inferred</groupId>
    <artifactId>freebuilder</artifactId>
    <version>1.6</version>
    <optional>true</optional>
  </dependency>
</dependencies>

Create your value type (e.g. Person) as an interface or abstract class, containing an abstract accessor method for each desired field. This accessor must be non-void, parameterless, and start with 'get' or 'is'. Add the @FreeBuilder annotation to your class, and it will automatically generate an implementing class and a package-visible builder API (Person_Builder), which you must subclass. For instance:

import org.inferred.freebuilder.FreeBuilder;

@FreeBuilder
public interface Person {
  /** Returns the person's full (English) name. */
  String getName();
  /** Returns the person's age in years, rounded down. */
  int getAge();
  /** Builder of {@link Person} instances. */
  class Builder extends Person_Builder { }
}

If you are writing an abstract class, or using Java 8, you may wish to hide the builder's constructor and manually provide instead a static builder() method on the value type (though Effective Java does not do this).

What you get

If you write the Person interface shown above, you get:

Person person = new Person.Builder()
    .setName("Phil")
    .setAge(31)
    .build();
System.out.println(person);  // Person{name=Phil, age=31}

Defaults and constraints

We use method overrides to add customization like default values and constraint checks. For instance:

@FreeBuilder
public interface Person {
  /** Returns the person's full (English) name. */
  String getName();
  /** Returns the person's age in years, rounded down. */
  int getAge();
  /** Returns a human-readable description of the person. */
  String getDescription();
  /** Builder class for {@link Person}. */
  class Builder extends Person_Builder {
    public Builder() {
      // Set defaults in the builder constructor.
      setDescription("Indescribable");
    }
    @Override public Builder setAge(int age) {
      // Check single-field (argument) constraints in the setter methods.
      checkArgument(age >= 18);
      return super.setAge(age);
    }
    @Override public Person build() {
      // Check cross-field (state) constraints in the build method.
      Person person = super.build();
      checkState(!person.getDescription().contains(person.getName()));
      return person;
    }
  }
}

Optional values

If a property is optional—that is, has no reasonable default—then use the Optional type. It will default to Optional.absent(), and the Builder will gain additional convenience setter methods.

  /** Returns an optional human-readable description of the person. */
  Optional<String> getDescription();

Prefer to use explicit defaults where meaningful, as it avoids the need for edge-case code; but prefer Optional to ad-hoc 'not set' defaults, like -1 or the empty string, as it forces the user to think about those edge cases. @FreeBuilder does not support nulls and will throw a NullPointerException if one is passed to a setter.

Collections and Maps

@FreeBuilder has special support for List, Set, Multiset, Map and Multimap properties:

Nested buildable types

@FreeBuilder has special support for buildable types like protos and other @FreeBuilder types:

Builder construction

Effective Java recommends passing required parameters in to the Builder constructor. While we follow most of the recommendations therein, we explicitly do not follow this one: while you gain compile-time verification that all parameters are set, you lose flexibility in client code, as well as opening yourself back up to the exact same subtle usage bugs as traditional constructors and factory methods. For the default @FreeBuilder case, where all parameters are required, this does not scale.

If you want to follow Effective Java more faithfully in your own types, however, just create the appropriate constructor in your builder subclass:

    public Builder(String name, int age) {
      // Set all initial values in the builder constructor
      setName(name);
      setAge(age);
    }

Implementation note: in javac, we spot these fields being set in the constructor, and do not check again at runtime.

Partials

A partial value is an implementation of the value type which does not conform to the type's state constraints. It may be missing required fields, or it may violate a cross-field constraint.

Person person = new Person.Builder()
    .setName("Phil")
    .buildPartial();  // build() would throw an IllegalStateException here
System.out.println(person);  // prints: partial Person{name="Phil"}
person.getAge();  // throws UnsupportedOperationException

As partials violate the (legitimate) expectations of your program, they must not be created in production code. (They may also affect the performance of your program, as the JVM cannot make as many optimizations.) However, when testing a component which does not rely on the full state restrictions of the value type, partials can reduce the fragility of your test suite, allowing you to add new required fields or other constraints to an existing value type without breaking swathes of test code.

IDEs

Follow your IDE's annotation processing instructions [Eclipse instructions; IntelliJ instructions].

GWT

To enable GWT serialization of the generated Value subclass, just add @GwtCompatible(serializable = true) to your @FreeBuilder-annotated type, and extend/implement Serializable. This will generate a CustomFieldSerializer, and ensure all necessary types are whitelisted.

Alternatives

AutoValue vs @FreeBuilder

Why is @FreeBuilder better than AutoValue?

It’s not! AutoValue provides an implementing class with a package-visible constructor, so you can easily implement the Factory pattern. If you’re writing an immutable type that needs a small number of values to create (Effective Java suggests at most three), and is not likely to require more in future, use the Factory pattern.

How about if you want a builder? AutoValue.Builder lets you explicitly specify a minimal Builder interface that will then be implemented by generated code, while @FreeBuilder provides a generated builder API. AutoValue.Builder is better if you must have a minimal API—for instance, in an Android project, where every method is expensive—or strongly prefer a visible-in-source API at the expense of many useful methods. Otherwise, consider using @FreeBuilder to implement the Builder pattern.

I used AutoValue, but now have more than three properties! How do I migrate to @FreeBuilder?

  1. Ensure your getter methods start with 'get' or 'is'.
  2. Change your annotation to @FreeBuilder.
  3. Rewrite your factory method(s) to use the builder API.
  4. Inline your factory method(s) with a refactoring tool (e.g. Eclipse).

You can always skip step 4 and have both factory and builder methods, if that seems cleaner!

Can I use both AutoValue and @FreeBuilder?

Not really. You can certainly use both annotations, but you will end up with two different implementing classes that never compare equal, even if they have the same values.

Proto vs @FreeBuilder

Protocol buffers have provided builders for ages. Why should I use @FreeBuilder?

Protocol buffers are cross-platform, backwards- and forwards-compatible, and have a very efficient wire format. Unfortunately, they do not support custom validation logic; nor can you use appropriate Java domain types, such as Instant or Range. Generally, it will be clear which one is appropriate for your use-case.

Wait, why "free"?

License

Copyright 2014 Google Inc. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.