builder patterns and exploding constructors

If you have a class heirarchy that adds more and more parameters to constructors as it goes down the (inheritance) chain, consider using builder pattern.

public class Animal {
    private String name;

    public Animal(String name) {
        this.name = name;
    }
}

public class Mammal extends Animal {
    private String furColor;

    public Mammal(String name, String furColor) {
        super(name);
        this.furColor = furColor;
    }
}

Consider using the builder patterns as shown here.

the problem I have with this technique is that: s this example trying to say that no inheritance chain may be required if we could put all the paramters of the chain of classes into into one class and just create a builder with some fields being optional and others throwing exception if missing?

If yes, how do we define behaviors on this object if it has so many fields i.e it’s essentially has data for many behaviors: animal, mammal, dog, cat etc.

Leave a comment

Design a site like this with WordPress.com
Get started