Dark theme | Light theme

June 18, 2010

Grails Goodness: Refactoring Criteria Contents

Grails adds a Hibernate criteria builder DSL so we can create criteria's using a builder syntax. When we have criteria with a lot of restrictions or conditional code inside the builder we can refactor this easily. We look at a simple criteria to show this principle, but it can be applied to more complex criteria's.

// Original criteria builder.
def list = Domain.withCriteria {
    ilike 'title', 'Groovy%'
    le 'postedDate', new Date()

// Refactor
def list2 = Domain.withCriteria {
    title delegate, 'Groovy%'
    alreadyPosted delegate

private void title(builder, String query) {
    builder.ilike 'title', query

private void alreadyPosted(builder) {
    builder.le 'postedDate', new Date()