开发者

case vs method builders, using named default parameters

I was about to use case classes with named default parameters as builders. For a simple example:

case class Person(name:String)
case class PersonBob(name:String = "Bob") {
   def build = Person(name)
}
val casePerson = PersonBob("case").build

But I could use methods as well:

object Builder {
  def personBob(name:String = "Bob"):Person = Person(name)
}
val methodPerson = Builder.personBob("method")

Some tradeoffs:

  • Method approach eliminates the need to create an object for each开发者_如何学C builder...saving cycles and memory.
  • Method approach has a bit leaner implementation code. No advantage for the usage syntax.
  • Methods can't be passed in as parameters to other builders for "builder composition". Functions can, but we are talking about methods here since functions don't support parameter defaults.
  • Case class approach allows me to persist builder instances (not needed now).
  • Case class approach would facilitate building an internal DSL at some point--but I think an external DSL is ambivalent to either approach.

Other considerations? Build a better builder some other way?


Confused am I: isn't the baked-in case class factory all that you need here, or am I missing something. IOW:

scala> case class Foo(bar:String="ab")
defined class Foo

scala> val f = Foo()
f: Foo = Foo(ab)

scala> f.bar
res2: String = ab
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜