Builder with conditional inclusion of an element

I was wondering how to make Builder with additional parameters more elegant:

what I have: an object with a name, identifier, age.

I have a difficult condition for including age, and I would like to send it to the developer for the success of this condition, but I would like it to be an elegant single liner with one parameter.

what i still have:

 Builder.name("name").id("id").age(age, complexCondition).build();

or

 Builder builder = Builder.name("name").id("id");
 if(complexCondition){
     builder.age(age);
 }

Are there any better options? I would like to resolve a condition where I have this without a constructor without an add-in and without recoding for each check of complex conditions.

upd: I'm looking for a solution without:

a) passing complexChecks or boolean to builder - not his job of validation by definition

b) without adding 3 lines for each test condition inside the method calling builder

+4
2

. . DSL . , .

, , if, , . ,

Builder builder = Builder.name("name").id("id");
if (complexCondition) {
    builder.age(age);
}

to

Integer age = null; // or whatever other default value you want
if (complexCondition) {
    age = somethingElse;
}
Builder builder = Builder.name("name").id("id").age(age);

, , bu, 4 , ,

Builder builder = Builder.name("name").id("id").age(computeAge());

, , IMO, :

Builder builder = Builder.name("name")
                         .id("id")
                         .age(computeAge());
+2

, ,

Builder.name("name").id("id").age(age, complexCondition).build();

Builder.name("name").id("id").age(age).ageCondition(complexCondition).build();

, complexCondition a Predicate<Something> ( Something - , ). , Builder build(), , .

build :

public SomeClass build() {
    SomeClass obj = new SomeClass();
    obj.setName(name);
    if (age != null && someCondition != null && someCondition.test(something)) {
        obj.setAge(age);
    }
    return obj;
}

, Something. .

, , :

public SomeClass build() {
    SomeClass obj = new SomeClass();
    obj.setName(name);
    if (age != null) {
        if (someCondition != null)) {
            if (someCondition.test(something)) {
                obj.setAge(age);
            }
        } else {
            obj.setAge(age);
        }
    }
    return obj;
}
+1

Source: https://habr.com/ru/post/1692493/


All Articles