Skip to content

How to define model

Shuji Konishi edited this page May 26, 2015 · 2 revisions

Basic policy of define model

1. Define getter methods only we need.

For example, the User has a field 'subscriptions_url'.
However maybe this field is not useful for every user.
So, we don't have to define this field in our model class.

We can add these field later, if necessary.
Or we can use get or opt methods directly.

val user
user.get("subscirptions_url")

2. Use get method as long as possible.

If the field might be null, or the field might not exist, we should use 'opt'.
Otherwise we should use 'get'.

For exapmle, user#email might be empty string. But you can use 'get'.

3. Use Trait, if necessary.

For example, user object might appear in any other objects.
And its structure might be little different each place.

In such a case, we can use Trait. Like this

trait UserAttributes {
  self: AbstractJson =>

  def login = get("login")
  def id = get("id").toLong
  //Other fields
}

case class User(value: JValue) extends AbstractJson with UserAttributes {
  //Define fields if necessary
}
case class RepositoryOwner(value: JValue) extends AbstractJson with UserAttributes {
  //Define fields if necessary
}