Salesforce Decode
Salesforcedecode
Back to questions
ApexBeginnernull-safetydefensive

Apply defensive null and empty collection handling in Apex

Real World Scenario

NullPointerException in production when optional lookup field blank on subset of records in batch.

Expected Answer

• Null-check relationship fields before dereferencing • Empty list iteration safe but query empty IN () throws • Optional chaining pattern with ternary or early continue • Validate API inputs at controller entry • Use String.isBlank for text fields not only null check • Unit tests include null field edge case records • Static analysis PMD null pointer rules in CI

Follow-Up Questions & Answers

Click to expand — each follow-up includes a direct, interview-ready answer

Direct answer: Null-check relationship fields before dereferencing Also consider: Empty list iteration safe but query empty IN () throws In practice: Optional chaining pattern with ternary or early continue Keep the solution simple and well-documented for the team.

Architect Perspective

Bulk data always includes incomplete records—null safety is not optional.