Monday, October 27, 2014
Grails Domain Classes and Enums
For a long time, I have been creating static int values to represent states in domain classes. For example, I would have something like the following:
1234567891011121314151617package org.exampleclass PluginPendingApproval { static final int STATUS_PENDING = 1 static final int STATUS_APPROVED = 2 static final int STATUS_REJECTED = 3 int status static constraints = { status blank: false, inList: [ STATUS_PENDING_APPROVAL, STATUS_APPROVED, STATUS_REJECTED ] }}Peter Ledbrook ( @pledbrook ) gave me some tips on how to handle this better using Enums. Enum values should always be in uppercase letters because they are constants in the fixed set. If we were to refactor the code above, it would something more like this:
123456789101112131415package org.exampleclass PluginPendingApproval { enum ApprovalStatus { PENDING, APPROVED, REJECTED } ApprovalStatus status static constraints = { status blank: false }}This works great for a single domain class, but what if I wanted to use the same Enum in two different domain classes. For example:
12345678910111213141516171819202122232425262728293031323334353637// PluginPendingApproval.groovypackage org.exampleclass PluginPendingApproval { static hasMany = [pluginPendingApprovalRequests: PluginPendingApprovalRequest] enum ApprovalStatus { PENDING, APPROVED, REJECTED } ApprovalStatus status static constraints = { status blank: false }}// PluginPendingApprovalRequest.groovypackage org.exampleclass PluginPendingApprovalRequest { static belongsTo = [pluginPendingApproval: PluginPendingApproval] enum ApprovalStatus { PENDING, APPROVED, REJECTED } ApprovalStatus status static constraints = { status blank: false }}I could keep do it this way where I have the enum code duplicated in two places, but that doesn’t follow the DRY principal.
Let’s refactor this and create a new Enum class that both domain classes can use:
package org.examplepublic enum ApprovalStatusEnum { PENDING, APPROVED, REJECTED}Now both of my domain classes can access the same Enum:
1234567891011121314151617181920212223242526272829// PluginPendingApproval.groovypackage org.exampleclass PluginPendingApproval { static hasMany = [pluginPendingApprovalRequests: PluginPendingApprovalRequest] ApprovalStatus status static constraints = { status blank: false }}// PluginPendingApprovalRequest.groovypackage org.exampleclass PluginPendingApprovalRequest { static belongsTo = [pluginPendingApproval: PluginPendingApproval] ApprovalStatus status static constraints = { status blank: false }}For more information on Enums in Groovy, see http://groovy.codehaus.org/Using+Enums
No comments: