I’m starting a blog.
Today, I learned a difference between using a Java primitive (int, double) and a Java class (Integer, Double) to define a Grails domain class.
class Student {
String firstName
double iq
}
Pretty easy, right? IQ is something that I don’t have, but many people do. I want to force new students to define their IQ.
Here’s my test. Make sure that student is invalid if no IQ is defined.
class StudentTests extends GrailsUnitTestCase {
// <snip> mocking stuff
def s = new Student(firstName:'Nate')
// We want to force iq to be defined
// No defaulting allowed
assertEquals "nullable" , s.errors["iq"]
// Test fails -- iq is already 0 !!!
}
When we define iq using Java’s “double” primitive type, the iq is automatcially initialized to zero.
Solution: Use Double or Integer, etc. classes if you don’t want a property to be initialized automatically.
Better:
class Student {
// Use the "Double" class instead of "double" primitive
Double iq
}

