design - Scala traits / cake pattern vs case classes -
in web application authorized user has @ least 4 "facets": http session related data, persistent data, facebook data, runtime business data.
i've decided go case class composition instead of traits @ least 2 reasons:
- traits mixing can cause name clashes
- i want free case class goodies pattern matching , copy method
i'd know experienced scalaists opinions on subject. looks traits and/or cake pattern should suitable such tasks i've mentioned above there problems... obvious not want implement fast , easy understand in depth using in future.
so decision have flaws , misunderstanding or right? related code looks this:
case class facebookuserinfo(name: string, friends: list[long]) case class httpuserinfo(sessionid: string, lastinteractiontime: long, reconnect: boolean) case class runtimequizuserinfo(recentscore: int) trait userstate { def db: user def http: httpuserinfo } case class connectinguser(db: user, http: httpuserinfo) extends userstate case class disconnecteduser(db: user, http: httpuserinfo, facebook: option[facebookuserinfo]) extends userstate case class authorizeduser(db: user, http: httpuserinfo, facebook: facebookuserinfo, quiz: runtimequizuserinfo) extends userstate
the third option use implicit converters aka "pimp library," not necessary since have control of code.
it depends on how opaque (or transparent) want aspect of object. can pretend plain old case class rest of world, internally make work using implicits. use of case class hold data appropriate feel it's awkward represent same object using 3 classes (connectinguser
, disconnecteduser
, authenticateduser
) depending on state of authentication.
for userstate
, provide extractor behaves case class:
object userstate { def unapply(state: userstate) = some(state.db, state.http) }
this can used in match state follows:
val user = connectinguser(user(), httpuserinfo("foo", 0, false)) user match { case userstate(db, http) => println(http) }
Comments
Post a Comment