Search code examples
javadesign-patternsmethod-chainingbuilder-pattern

How to implement a checked builder pattern in Java


I'm trying to implement a checked builder pattern similar to how it's described in this: https://dev.to/schreiber_chris/creating-complex-objects-using-checked-builder-pattern

The result I'm trying to reach is as follows:

Builder builder = new Builder('TestVal')
    .when('this').then(new Set<String> {'val1','val2'})
    .when('that').then(new Set<String> {'val3','val4'});

And the resulting object would contain a collection with any number of whens with the associted thens e.g. a Map like this (the param for when() is unique):

'this' => ['val1','val2'],
'that' => ['val3','val4']

I'm struggling with a couple things:

  1. How to associate the values passed into then() with the value passed into when()
  2. How to require then() be called after when(). (e.g. - .when('this').when('that') //invalid

Solution

  • The easiest way is to use multiple interfaces to enforce your call ordering and then use that knowledge to associate your items. For example, something along these lines:

    interface Then{
        When then(Set<String> values);
    }
    
    interface When{
        Then when(String condition);
    }
    
    class Builder implements When, Then{
    
        public static When create(){ return new Builder(); }
    
        private Map<String, Set<String>> storedMappings = new HashMap<>();
        private String currentCondition;
    
        private Builder(){ }
    
        public Then when(String condition){
            currentCondition = condition;
            return this;
        }
    
        public When then(Set<String> values){
            storedMappings.put(currentCondition, values);
            return this;
        }
    }