Groovy is less strict compared to other programming languages. See the following examples.
Groovy
// true is true, false is false :-)
assert true
assert !false
// non-empty collections are true, empty collections are false
assert [1, 2, 3]
assert ![]
// same with maps
assert ['one' : 1]
assert ![:]
// non-empty strings are true, empty strings are false
assert 'a'
assert !''
// non-zero numbers are true, zeros are false
assert 1
assert 3.5
assert !0
// non-null object references are true, null references are false
assert new Object()
assert !null
With this knowledge, you can simplify your code noticeably. Instead of writing this:
Groovy
def competition = api.productExtension('Competition') // returns a collection
if (competition != null && !competition .isEmpty()) {
// do something with the competition records
}
You can write just:
Groovy
def competition = api.productExtension('Competition') // returns a collection
if (competition) { // equals to true if the competition is both non-null and non-empty
// do something with the competition records
}
Checking for non-null and non-empty arrays is a powerful feature which will save you a lot of typing. But note that if you actually want an empty collection to be a valid result, you need to explicitly check for null.
Also, pay attention to checking for non-null numbers like this:
Groovy
def n = product.attribute1 // we're expecting a number or null
if (n) { // we need to explicitly check for non-null reference here, otherwise we would filter out zeros
return 'Yay, I'm a non-null number'
} else {
return 'But zeros are numbers too!'
}
This would filter out zeros as well as zero is evaluated to false.