-
Notifications
You must be signed in to change notification settings - Fork 16
Nesting
Pierre Andrews edited this page Dec 30, 2013
·
3 revisions
In addition to mixing all your argument traits together into one super trait, you can also "nest" the traits inside each other. Eg., given these basic argument classes*:
trait DbConnection extends FieldArgs {
var host: String = _
var port: Int = _
}
trait UserInfo extends FieldArgs {
var id: String = _
}
You could either combine mix those traits together:
trait FlatArgs extends DBConnection with UserInfo
or you could nest them together:
trait NestedArgs extends FieldArgs {
var db: DBConnection = new DBConnection {}
var user: UserInfo = new UserInfo {}
}
This would result in the following argument names:
-
FlatArgs
-->--host <host> --port <port> --id <id>
-
NestedArgs
-->--db.host <host> --db.port <port> --user.id <id>
In general, I start w/ mixing all of the trait together. However, there are a few cases where I use the nesting approach
- Multiple arguments of the same type. Suppose that an app needed two different user ids, eg. to compare them? You couldn't reuse the
UserInfo
trait for both users. But you could do it like this:
trait MyArgs extends FieldArgs {
var user1: UserInfo = _
var user2: UserInfo = _
var db: DBConnection = _
}
- Effective code re-use. Imagine that across your entire code base,
DBConnection
can get used to connect to completely different databases. Suppose that you use it to connect to both a user database, and also a database used to track system statistics. They may even exist on different hosts. You can put the basic methods to connect to a database inDBConnection
, but then you can reuse create additional traits:
trait UserDB extends FieldArgs {
var userdb: DBConnection = _
}
trait SystemStatDB extends FieldArgs {
var systemstatdb: DBConnection = _
}
This way, we've created unique names for both databases, so we can define different defaults for both connections.
- this is a really minimal example -- imagine those classes also had helper methods for it to be more compelling. Furthermore, they really should extend from something other than
FieldArgs
, as described in the Best Practices section.