AlgoViz

Builder

medium 50 min

The Builder collects the parts of a complex object one by one, checks them together, and creates the object in a single moment.

Watch lesson4:31

Where it shows up

The same pattern appears across everyday software.

  • OkHttp Request.Builder

    A request is created from its builder, which must have a url. Request.newBuilder returns a builder filled with the request's values, the way back.

  • java.net.http.HttpRequest

    The documentation says that a built request is immutable and can be sent several times, that build throws IllegalStateException if no URI was set, and that copy duplicates a builder.

  • Java StringBuilder

    append returns the builder, and toString gives the immutable String. It collects one sequence and has no rules, so it is the simplest relative of the pattern. It is documented as not safe for several threads.

  • Lombok @Builder

    Generates the builder class. @Singular adds elements one by one, toBuilder = true adds the way back, @Builder.Default keeps initial values.

  • Android AlertDialog.Builder

    Title, message, icon and buttons are set on the builder, and create returns the dialog with the arguments supplied to the builder.

  • Protocol Buffers in Java

    Messages are immutable, like a Java String. Each message class has a generated Builder class, and nested builders change deep fields.

  • jOOQ

    SQL is written as a chain of calls. The steps return types such as SelectWhereStep, so the compiler knows which clause may come next: a staged builder.

  • Knex

    A JavaScript query builder. The chain starts with a table name and ends by executing the query or turning it into a string.

  • Java Locale.Builder

    Checks its parts and can be reused: clear resets all fields to their default values.

  • Guava ImmutableList.Builder

    May be reused. Each new list contains all the elements of the ones created before it, a contract that surprises people who expect a reset.

  • Rust API Guidelines

    Recommend builders for complex values and describe two kinds: non-consuming ones that can be used again, and consuming ones that give up the builder.