Wednesday 28 June 2017

Which is better != null or !isEmpty() ?


Is this in regards to String?  If so, I usually use String.isBlank( stringToCheck ).  This checks for null, empty and all whitespace.

If this is in regards to collections, you might have to check both:

if ( myList != null && !myList.isEmpty() ) ...

If you know that your collection is not null (because you allocated it, or it's the result of a query), then I prefer !.isEmpty() over .size() > 0:

This:

if ( !myList.isEmpty() ) ...

Not this:

if ( myList.size() > 0 ) ...

They have the same effect, but I think that .isEmpty() expresses the intent better, i.e. I want to know if the list is empty or not.  I don't actually care what its size is.

No comments:

Post a Comment

Batch Apex

1. What are transaction limits in apex? Total number of SOQL queries issued1 - 100 Total number of records retrieved by SOQL queries - 50...