Andna
Andna

Reputation: 6689

named parameters vs type-safe builder pattern

I am a scala newbie and I was wondering, if builder patterns, like the one described in http://blog.rafaelferreira.net/2008/07/type-safe-builder-pattern-in-scala.html have some usage in scala >= 2.8.

With named parameters and default arguments I can declare which arguments are mandatory (by not giving them default value) and I can pass constructor arguments in any order I want (by using named parameters).

Is there any advantage of having builder then?

Upvotes: 2

Views: 598

Answers (2)

WeiChing 林煒清
WeiChing 林煒清

Reputation: 4479

Reason why I want builder pattern :

  1. consistency , since constructor is method and method is convertible with function.

    • strict function -> partial applied function or curried function
    • strict method -> N/A (not allowed in Scala, you need convert it into function but that lose parameter informations.)
    • strict class -> same as above, or use builder pattern to partial applied the constructor.
    • and partial applied type , for example type State[S, A] = StateT[Eval, S, A]
  2. Do you like partial applied function, I do, for functional programming , you are usually passing function around, and you don't want always pass it accompanying with its partial arguments, so you partial applied it and pass just one value along.
    And given 1, it should go the same for method and class.

  3. separation the construction into different place. (similar to 2.)
  4. cache computation. check this answer https://stackoverflow.com/a/4916606/2130573

Upvotes: 0

som-snytt
som-snytt

Reputation: 39587

The builder pattern allows an object that is partially constructed (according to some arbitrary criteria).

For example, you might have an object that is partially initialized at startup, but requires further parameterization before usage.

It's not possible to express that in a single parameter list (or list thereof), except if one of the args captures the partial configuration (which kind of defeats the utility).

Upvotes: 1

Related Questions