DEV Community

Discussion on: Fluent Plain Old Object Builder Interface Pattern

Collapse
tacsiazuma profile image
Krisztian Papp

The main idea behind using a builder is so that you can hide the concrete implementation of an object but still be able to create an instance of it via a public interface.

That's more like the idea behind the factories or creational patterns in general.

"The intent of the Builder design pattern is to separate the construction of a complex object from its representation."
A POJO is not so complex. The only thing you could achieve with this approach is creating immutable DTO's, which failed when you added setters to the class.

Basically, if you want to achieve immutability with the DTO's, then you should create an inner static class Builder, which is mutable. And implement that fluent API on it. When you invoke the build method, you should invoke a private constructor of the outer class which is accessible by the builder and pass the builder instance to it. Then just pass its fields to the outer class instance.

 class Immutable {
    private final String whatever;

    private Immutable(Builder builder) {
        this.whatever = builder.whatever;
    }

    public static class Builder {
        private String whatever;

        public Builder withWhatever(String whatever) {
           this.whatever = whatever;
           return this;
        }
        public Immutable build() {
           return new Immutable(this);
        }

    }

  }

In this way, you aren't violating any checkstyle rule, got rid of the setters, could make those fields in the outer class final. But this isn't really a builder, because you should think about default values, validation, different implementations and so on.