How to simplify this code in Groovy that sets object properties if they are null?

I use Grails to set properties in a domain class if the property is not null. Currently, the code looks something like this:

def product = Product.getById(5);

if (!product.Name) {
    product.Name = "Default Product"
}
if (!product.Price) {
    product.Price = 5;
}
if (!product.Type) {
    product.Type = "Shampoo"
}

What is the best way to implement this code in Groovy? I managed to simplify it:

product.Name = product.Name ?: "Default Product"
product.Price = product.Price ?: 5
product.Type = product.Type = "Shampoo"

But I would like to do something like this (invalid code):

product {
    Name = product.Name ?: "Default Product",
    Price = product.Price ?: 5,
    Type = product.Type ?: "Shampoo"
}

What would you guys recommend to me?

+3
source share
2 answers

Use the method method within the last example:

product.with {
    Name = Name ?: "Default Produce"
    Price = Price ?: 5
    Type = Type ?: "Shampoo"
}
+5
source

Not sure if it's easier, but perhaps more reusable:

def setDefaults(obj, Map defaults) {
    defaults.each { k, v -> obj[k] = obj[k] ?: v }
}

setDefaults(product, [Name: 'Default Product', Price: 5, Type: 'Shampoo'])
0
source

All Articles