[SalesForce] Null check OR isEmpty Check

I have checked many posts but still not clear.
A SOQL query returns a list but if SOQL finds no records then it will return an empty list or it will be null?

When should i go for isEmpty check or when for null check?

Thanks

Best Answer

The straight SOQL accounts = [select id, .. from Account ...]

always returns a list

You can usually avoid even having to test for list empty by coding your methods to accept lists as arguments and otherwise use for loop processing as in

for (Account a: accounts) { // if accounts is empty, loop does nothing
    // do work
}

someReturnType myMethod(Account[] accounts) {
   for (Account a: account) {
      // do work
   }
}

Otherwise use accounts.isEmpty() or accounts.size() == 0

testing for null is unnecessary in a well-designed application that uses lists and maps as the core internal data structures. Personally, if I ever get a null value for a list, I prefer the null exception to occur during unit testing as it means I didn't design my code correctly to operate with lists throughout (or I forgot to init a list to empty).

N.B.

For DML, you never need to test for list empty as SFDC will do nothing if passed an empty list

Use:

update accounts; // does not burn a DML limit if list is empty

Don't use (wastes a line of code):

if (!accounts.isEmpty())
   update accounts;
Related Topic