dukeofgaming
dukeofgaming

Reputation: 3198

Using traits for horizontal domain class reuse in Grails, a good idea?

So I want to create 3 plugins which include domain classes and a restful service, and who each build on top of each other.

Conceptually, they would "inherit" the base model this way:

Record > Person > User

However I have Read From The Friendly Manual that inheritance may cause some performance issues.

Then it crossed my mind that since Groovy has horizontal reuse capabilities (i.e. traits), I may very well just define everything in the trait and then implement the trait in the domain class.

Composing domain classes is not an option for me because of the renaming of the fields, and well, the loss of the convenience of IDE auto-completion.

My two questions are:

Upvotes: 2

Views: 673

Answers (1)

Emmanuel Rosa
Emmanuel Rosa

Reputation: 9885

The Trait source code should be in

  1. Grails 2: src/groovy/[package][whatever.groovy]
  2. Grails 3: src/main/groovy/[package][whatever.groovy]

For example: src/main/groovy/com/my/package/foo.groovy

The main issue you'll have is that you'll loose the ability to perform polymorphic queries. For example, with inheritance you can do something like this:

def everything = Record.list()

and everything would contain Record, Person, and User instances. Kind of like a SQL union query. When using Traits instead of inheritance you loose this ability.

Upvotes: 5

Related Questions