Java – name for the Builder Pattern where the Builder is implemented via interfaces so certain parameters are required

design-patternsjava

So we implemented the builder pattern for most of our domain to help in understandability of what actually being passed to a constructor, and for the normal advantages that a builder gives. The one twist was that we exposed the builder through interfaces so we could chain required functions and unrequired functions to make sure that the correct parameters were passed. I was curious if there was an existing pattern like this.

Example below:

public class Foo
{
   private int someThing;
   private int someThing2;
   private DateTime someThing3;

   private Foo(Builder builder)
   {
       this.someThing = builder.someThing;
       this.someThing2 = builder.someThing2;
       this.someThing3 = builder.someThing3;
   }

   public static RequiredSomething getBuilder()
   {
       return new Builder();
   }

   public interface RequiredSomething { public RequiredDateTime withSomething (int value); }
   public interface RequiredDateTime { public OptionalParamters withDateTime (DateTime value); }
   public interface OptionalParamters { 
      public OptionalParamters withSeomthing2 (int value); 
      public Foo Build ();}

   public static class Builder implements RequiredSomething, RequiredDateTime, OptionalParamters 
   {
      private int someThing;
      private int someThing2;
      private DateTime someThing3;

      public RequiredDateTime withSomething (int value) {someThing = value; return this;}
      public OptionalParamters withDateTime (int value) {someThing = value; return this;}
      public OptionalParamters withSeomthing2 (int value) {someThing = value; return this;}
      public Foo build(){return new Foo(this);}
   }
}

Example of how it's called:

   Foo foo = Foo.getBuilder().withSomething(1).withDateTime(DateTime.now()).build();
   Foo foo2 = Foo.getBuilder().withSomething(1).withDateTime(DateTime.now()).withSomething2(3).build();

Best Answer

What you are doing is called a fluent interface.

From Fowler's article:

In essence we create the various objects and wire them up together. If we can't set up everything in the constructor, then we need to make temporary variables to help us complete the wiring - this is particularly the case where you're adding items into collections.

Which is where @Frank was talking about "Phantom Types". Also Fowler says

Probably the most important thing to notice about this style is that the intent is to do something along the lines of an internal DomainSpecificLanguage. Indeed this is why we chose the term 'fluent' to describe it, in many ways the two terms are synonyms. The API is primarily designed to be readable and to flow.

The way I have seen this discussed is to use "fluent" as an adjective, so in your case it would be a "fluent builder".