Sunday, March 22, 2009

Grails domain object modeling with Groovy enums

I had a need to use enumerations within my object model in my Grails app today. I wrote up a Google Sites page about my solution. I am using Grails 1.1 for this solution.

5 comments:

  1. Looks like the link to your sites page is protected - it asks me to log in to Pintail Consulting...

    ReplyDelete
  2. @Mike Hugo

    Try now Mike. I changed the access control to allow anyone to view the pages under my Groovy and Grails Google Sites area. Thanks for taking a look. Having a lot of fun playing with Grails 1.1.

    ReplyDelete
  3. Hey Chris, nice job with an easily readable enums example (that comes up often in Google!) in Grails. Since your result is very popular, you may want to refactor a little bit per these comments from Burt Beckwith on the grails user mailing list:

    Burt Beckwith burt@burtbeckwith.com via grails.codehaus.org to user

    show details Aug 27 2011

    I think they're [enums] a good option. They restrict the valid values without a constraint (you don't need the inList constraint since you can't have a Location value that isn't an enum instance) and are persisted by default as the name of the instance, so the values are clear in the database.

    Note that you don't need to have a list() method - there's already a static values() method on all Enums that returns the enum values in the order declared in the class. Plus it will always be in sync with the code - using a custom method runs the risk of someone adding or removing a value but forgetting to update the list() method.

    ReplyDelete
  4. Updated the example per Burt's comments.

    ReplyDelete