Best practices for using null-safe operators

Be aware of the consequences of using the null-safe operators. If the null-safe expression returns a value of null, your subsequent code must be able to handle that value. If the argument on the left of a null-safe operator is null, the expression returns a value of null, or its equivalent for a primitive type. For example, using a null-safe operator in an expression that returns an int value produces a value of 0 if the argument on the left of the operator is null.

Do not use null-safe operators merely to avoid any null-pointer exceptions. Using these operators is a signal to other code developers that the code path can accept and return null values. Use the null-safe operators only if your code does not need to perform additional actions for an object path expression that evaluates to null.

Do not use null-safe operators if you know that an object is never going to be null. For example, if you create a new object, subsequent code has no need to use null-safe operators on that object.

uses gw.api.util.DateUtil

var startTime = DateUtil.currentDate()
// No need to use null-safe operators to call methods on startTime
var terminationTime = startTime.addHours(2) // CORRECT
var halfTime = startTime?.addHours(1) // DO NOT USE THIS FORM. startTime is never null.

Similarly, if a function in a class uses the this name to reference the current object, do not use the null-safe operators, such as this?.methodName(). The this object never has a value of null.