Search code examples
oopdesign-patternssolid-principles

Builder Pattern and LSP


I was going through Builder pattern and had a couple of question that I thought needed clarification

  1. Is builder pattern implemented through Abstract class or through interfaces. There are few posts that uses interface https://sourcemaking.com/design_patterns/builder
    https://refactoring.guru/design-patterns/builder
    ...can list more
    and others uses abstract class https://www.dofactory.com/net/builder-design-pattern

Note: The way I think is that it should be implemented using Abstract class. This rationale is based on the assumption that this way I may/may not implement them in derived class (as there could be a possibility that a few concrete class does not implement them)...
This assumption could be entirely wrong though.

  1. If the above assumption is wrong then wont it violate LSP. Since one condition in LSP say that you cant have "not implemented methods" in your derived class.

Or I have misunderstood it completely...


Solution

  • This became too long for a comment...

    The patterns from the GoF book are older than Java. It was Java that later introduced the (silly) distinction between interface and abstract class. When the GoF refers to an interface, they simply mean an abstraction, and you can implement it using any language feature that enables abstraction.

    That being said, the GoF Builder Pattern is overcomplicated. The pattern is useful even without polymorphism. And I think that is how it's most often implemented. If you're using Java, that would be Josh Bloch's Builder Pattern from Effective Java.

    I don't mean to dismiss the LSP question, but if the real goal here is to learn to use a Builder effectively, then my advice is to ignore the (outdated) version from the GoF and look at a modern implementation where that question doesn't arise. If you really wanted to ask about the LSP, then I suggest a new question focused specifically on that topic, separate from the Builder Pattern.

    To more directly address the questions in the OP,

    1. The builder pattern can be implemented through abstract classes or through interfaces. It does not matter which. Modern implementations more often use neither.
    2. LSP conformity will depend on how you implement (and document) the pattern. It would be possible to violate the LSP (or not) using interfaces or abstract classes. Eliminating both eliminates this question.