3

I was reading through this article on design patterns in Scala, and they presented the argument that the Builder pattern is relevant in Java, as it allows for code such as:

CarBuilder carBuilder = new CarBuilder()
carBuilder.setSeats(2)
carBuilder.setSportsCar(true)
carBuilder.setTripComputer(true)
carBuilder.setGPS(false)
Car car = carBuilder.build()

versus the more confusion-prone form:

Car car = new Car(2, true, true, false)

They later stated that:

In a language like Scala which lets you name arguments while passing them in, the builder pattern is mostly obsolete...

Is this a similar situation for Python, as you're able to name keyword arguments in any call, or is there some reasonable application for this design pattern?

Sean Pianka
  • 2,157
  • 2
  • 27
  • 43
  • You can pass a builder around before `build()`ing, having different aspects of initialization performed at different times and locations. Also, there may be complex logic involved in how to create an object - or even *which*. 'Fluent' APIs are often only possible through builder pattern. – JimmyB Nov 30 '16 at 15:36

2 Answers2

7

An authoritative answer can be found in the book Effective Java. Chapter 2 is where the famous Java Builder pattern by Josh Bloch originates. On page 15, it states,

The Builder pattern simulates named optional parameters as found in Ada and Python.

So the answer to your question is an emphatic yes. There is no need to simulate a pattern that exists natively in a language.

You may also be interested in this popular thread: Does functional programming replace GoF design patterns?

Community
  • 1
  • 1
jaco0646
  • 15,303
  • 7
  • 59
  • 83
1

As a Scala programmer I would say that this is the case. I've implemented an API where the Java code used a "Builder" while the Scala code was just regular Scala code. I belive the same could be done in Python without any hindrance and using a builder pattern is not strictly required to have that behaviour. Named parameters work way better, are more readable and usually lead to cleaner solutions.

Chobeat
  • 3,445
  • 6
  • 41
  • 59