vendredi 31 mai 2019

Should Builder.build() return a default state?

Using the Builder pattern there is always the question whether the fields do have a default value or not? I cannot find a reliable source where that's clearly defined...

The problem is readability: What is Car.Builder().build() returning? I always need to check the specific implementation of the Builder to see which default values are used. Shouldn't Builder be used to create complex objects which do not have a simple default state by definition?

An alternative would be to check whether all mandatory fields are set inside of the build() method:

fun build() : Car {
    return if (doors != null && hp != null) Car(doors, hp, color) // color can be null
    else throw IllegalArgumentException("Door count and HP is mandatory!")
}

...or is this considered bad practice?

Aucun commentaire:

Enregistrer un commentaire