Notes
List<Account> hotAccounts = [SELECT Id, Name, Rating FROM Account WHERE Rating = 'Hot'];
if (hotAccounts != null && !hotAccounts.isEmpty()) {
System.debug('Hot Accounts found: ' + hotAccounts.size());
for (Account acc : hotAccounts) {
System.debug('Account Name: ' + acc.Name + ', Rating: ' + acc.Rating);
}
} else {
System.debug('No hot accounts found.');
}
Null Check (accountList != null
):
- Prevents Null Pointer Exceptions: If you attempt to access or perform operations on a list or variable that is
null
, it will result in a null pointer exception, causing your code to fail. Checking for null
ensures that you don’t try to work with something that doesn’t exist in memory.
- Indicates Whether the List Was Initialized: Sometimes, lists may not be initialized if, for example, a query didn't return any results, or the list wasn't assigned any values. The
null
check tells you whether the list was initialized or declared properly.
- Reduces Unnecessary Operations: If the list is
null
, the program can exit early or handle it properly without running further code that relies on the list, improving efficiency.
Empty Check (!accountList.isEmpty()
):
- Ensures There’s Data to Process: After confirming that the list is not null, the empty check ensures that the list contains actual records. A list can exist (not
null
) but still be empty (size = 0
), meaning there are no items in it to process.
- Prevents Looping Over Empty Lists: Without an empty check, you might accidentally loop over an empty list, which could result in wasted iterations and potentially cause bugs if your code assumes the presence of records.
- Allows Better Handling of Edge Cases: By knowing when the list is empty, you can provide more accurate feedback to the user or debug logs, such as "No records found" rather than assuming that the list always has values.