1

I need similar object as grails domain object which does not need persisting. In order that I do not have to make changes in 2 places for any field changes, is it a good idea to extend the domain class so that I can get the benefits of single set of fields. Although all related objects and collections will need to be redone.

2
  • 1
    Domain class contains a lot of other things also. So instead of extending the domain class, put your fields in a groovy file and extend that in your domain class. Jan 6, 2016 at 6:58
  • 3
    also consider using a trait to not lock yourself into some inheritance hell
    – cfrick
    Jan 6, 2016 at 7:45

1 Answer 1

2

@cfrick is spot on. A Groovy trait is a very good way to go. You can get a full example here (bad name for the project, I know). Here's a quick example:

// MyTrain.groovy: Put this in src/main/groovy/my/package
package my.package

trait MyTrait {
    Integer number
    String something
}

// MyDomainClass.groovy: This goes with the other domain classes.
package my.package

class MyDomainClass implements MyTrait {
    /*  
     * number and something properties are available here.
     * They become table columns.
     */  

    static constraints {
        /*  
         * And you can place constraints on them,
         * as it they had been declared in this class.
         */  
    }   
}
1
  • Dead link / non-existing bitbucket repo. But great example! Thanks!
    – Michael
    Jan 8, 2019 at 14:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.