Null-safe Groovy code

   Exchange Pre-configured Maestro services.  |   Platform Developer |  All versions   This feature is related to v5.1 and higher.

Using some simple techniques to write null-safe code avoids many common causes of run time errors due to NullPointerExceptions. For a detailed list of operators, see Groovy Language Documentation > 1.2 Operators.

Safe navigation operator

The Safe Navigation operator (?.) is used to avoid a NullPointerException where the existence of a valid object at run time is not guaranteed. When you reference an object, you might need to verify that it is not null before accessing methods or properties of the object. Using if statements to perform this check when navigating deep into object graphs quickly becomes a lengthy and annoying coding exercise. For example:

// Get the firstName request parameter and trim any leading or trailing white space
firstName = request.getParameter('title')
if(firstName != null){
    firstName = firstName.trim()
}

Using the Safe navigation operator, these if statements can be avoided and a more concise null-safe coding style can result:

firstName = request.getParameter('title')?.trim()

In the statement above, if the request parameter is null, the trim function will not be executed and a NullPointerException will be avoided.

The Elvis operator

The Elvis operator (?:) is a shortening of the ternary operator and is convenient for assigning to a variable a sensible default value where it would otherwise be set to null. In the code examples below, the ternary operator requires you to repeat the value you want to assign if the value tested is not null or false, where the Elvis operator uses the value tested if it is not null or false.

// Ternary operator
firstName = request.getParameter('title') ? request.getParameter('title') : ''
// Elvis operator
firstName = request.getParameter('title') ?: ''