Sunday, May 25, 2025

No More Null Crashes! 5 Simple Apex Tips to Make Your Code Safer

Tired of late-night debugging sessions because of annoying null errors in Apex? We’ve all been there. These simple checks will help you handle lists, sets, maps, and objects with confidence — and fewer crashes.


1. != null“Does it even exist?”

This is your first safety net. Before you interact with any variable — object, list, set, or map — check if it's not null.

When to use: Always. This is your go-to check to prevent null reference exceptions.

Example:


Lead leadRecord = [SELECT Id, Email FROM Lead LIMIT 1];

if (leadRecord != null) {

    System.debug('Lead record exists!');

}

Note: This confirms the variable is present, but not whether it contains useful data.


2. !isEmpty()“Is there anything inside?”

A quick and clean way to see if your list or set has at least one item.

When to use: Ideal for lists and sets where you're only interested in whether there's data, not how much.

Example:


List<Case> openCases = [SELECT Id FROM Case WHERE Status = 'Open'];

if (!openCases.isEmpty()) {

    System.debug('There are open cases!');

}

Why it's better: It's more readable than writing size() > 0.


3. size() > 0“How many items are there?”

This tells you the number of elements in a list, set, or map — and whether it's empty or not.

When to use: Useful when you’re working with maps, or need the actual count.

Example:


Map<Id, Product2> productMap = new Map<Id, Product2>(

    [SELECT Id, Name FROM Product2 WHERE IsActive = TRUE]

);

if (productMap.size() > 0) {

    System.debug('Found ' + productMap.size() + ' active products.');

}


4. contains()“Is this item in there?”

Perfect for checking if a list or set contains a specific item.

When to use: Great for filtering or conditionally running logic.

Example:


Set<String> approvedStatuses = new Set<String>{'Approved', 'Validated'};

String currentStatus = 'Approved';


if (approvedStatuses.contains(currentStatus)) {

    System.debug('Status is approved.');

}


5. containsKey()“Is this key in the map?”

When working with maps, use this to verify a key exists before accessing it.

When to use: Always check before using map.get() to avoid surprises.

Example:


Map<Id, User> userMap = new Map<Id, User>(

    [SELECT Id, Name FROM User WHERE IsActive = TRUE]

);

Id targetUserId = UserInfo.getUserId();


if (userMap.containsKey(targetUserId)) {

    System.debug('User found in map!');

}


No comments:

Post a Comment