Incorrect safe navigation warning

Issue #2325 resolved
Aidan Harding created an issue

The code inspection for use of the safe navigation operation issues a warning in the following code which is actually correct:

Object fieldValue = record.get(field);

if(String.valueOf(fieldValue)?.length() > fieldSize) {
    // do something
}

Apex defines the result of an inequality where one side is null to always be false (see https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_expressions_operators_understanding.htm). So, the safe navigation is doing what I intended: only execute the body of the if-statement when the field value is long. If the field is null, don’t do the body.

You could argue that this code is too “clever”, but it is well-defined by Apex and not a runtime error so I don’t think that it should be flagged with a warning.

Comments (2)

  1. Scott Wells repo owner

    Fix committed for the next build. Instead of disabling it altogether, I made it an inspection configuration option that defaults to enabled but can be disabled if so desired:

  2. Log in to comment