This is motivated by this answer to a separate question.
The builder pattern is used to simplify complex initialization, especially with optional initialization parameters). But I don't know how to properly manage mutually exclusive configurations.
Here's an Image
class. Image
can be initialized from a file or from a size, but not both. Using constructors to enforce this mutual exclusion is obvious when the class is simple enough:
public class Image
{
public Image(Size size, Thing stuff, int range)
{
// ... initialize empty with size
}
public Image(string filename, Thing stuff, int range)
{
// ... initialize from file
}
}
Now assume Image
is actually configurable enough for the builder pattern to be useful, suddenly this might be possible:
Image image = new ImageBuilder()
.setStuff(stuff)
.setRange(range)
.setSize(size) // <---------- NOT
.setFilename(filename) // <---------- COMPATIBLE
.build();
These problems must be caught at run time rather than at compile time, which isn't the worst thing. The problem is that consistently and comprehensively detecting these problems within the ImageBuilder
class could get complex, especially in terms of maintenance.
How should I deal with incompatible configurations in the builder pattern?