Builder Template Validation - Effective Java

In paragraph 2 of effective Java (2nd edition), the author mentions the following about superimposing invariants on parameters when using Builders:

It is very important that they are checked after copying the parameters from the builder to the object and that they are checked in the fields of the objects, and not against the fields of the builder (paragraph 39). If any invariants are violated, the assembly method should throw an IllegalStateException (paragraph 60).

Does this mean that after the build method has created the target, it must be passed to the verification procedure for any necessary checks?

Also, can someone explain the reason for this?

+4
source share
2 answers

Validation of an object is an integral part of creating an object using collectors. Although you can have a separate procedure that performs verification, this separation is not required: the verification code can be part of the function that performs the assembly. In other words, you can do it

TargetObject build() {
    TargetObject res = new TargetObject();
    res.setProperty1();
    res.setProperty2();
    validate(res); // This call may throw an exception
    return res;
}

void validate(TargetObject obj) {
    if (...) {
        throw new IllegalStateException();
    }
}

or that:

TargetObject build() {
    TargetObject res = new TargetObject();
    res.setProperty1();
    res.setProperty2();
    if (...) {
        throw new IllegalStateException();
    }
    return res;
}

It is important that validation occurs after, and not earlier, the construction of the target object. In other words, you need to check the state of the object, not the state of the builder.

+4
source

builder build() , . , . . , , . (EJ item 39) , , .

+3

All Articles