Software Crafter

Using the blank constraint in Grails

I have just begun using Grails for Less Out and have been accustomed to using the ‘def’ keyword when declaring any variables. I really don’t have any particular reason in doing it this way, I just wanted to use the features of Groovy when ever possible … when in Rome.

This past weekend I was working on an Action which is passed a Command, the Command has a few constraints and one of them was:

static constraints = {
  name blank:false, nullable:false
}

This is pretty harmless, but I was not able to get a test to pass. I was never able to get the blank constraint to fail.

I then started to hunt through the Grails source code and found the BlankConstraint source. More specifically, I think the culprit (somebody please prove me wrong here) is the ‘supports’ method.

public boolean supports(Class type) {
        return type != null && String.class.isAssignableFrom(type);

}

One thing I left out is I declared the 'name' variable as:

def name

The ‘supports’ method checks if String is assignable from the passed in type, and since you can think of def as an Object (documentation) then the method will return false.

Once I changed my declaration to:

String name

Then all my test validations worked correctly.

I could see how Grails would not want to throw an exception in this scenario (especially given this late in the game) but a log statement stating it is skipping over this contraints would be very much appreciated.