Safe Navigation Patterns

Overview

Null dereference bugs are common in Salesforce codebases with deep relationship traversal and optional fields.

Use explicit null-safety patterns consistently so code is both safe and readable.

Consensus Best Practices

Core Patterns

Pattern 1: Guard Clause Entry

public static String getAccountName(Contact c) {
    if (c == null || c.Account == null) return null;
    return c.Account.Name;
}

Pattern 2: Safe Navigation Operator

String accountName = contact?.Account?.Name;
String ownerEmail  = contact?.Account?.Owner?.Email;

Pattern 3: Null-Safe Map Access

Contact oldRow = oldMap?.get(row.Id);
if (oldRow == null) return;

Pattern 4: Fallback Defaults

String label = contact?.Preferred_Name__c;
if (String.isBlank(label)) {
    label = contact?.FirstName != null ? contact.FirstName : 'Customer';
}

When to Avoid Overuse

Common Failure Modes