+ Start a Discussion
ethan huntethan hunt 

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

Best Answer chosen by ethan hunt
GlynAGlynA
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.

Glyn Anderson
Sr Developer | System Analyst | ClosedWon | closedwon.com
Certified Developer | Certified Advanced Administrator
Twitter: @GlynAtClosedWon

All Answers

sunny.sfdcsunny.sfdc
I believe isEmpty() is better. It checks both null and empty string.
GlynAGlynA
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.

Glyn Anderson
Sr Developer | System Analyst | ClosedWon | closedwon.com
Certified Developer | Certified Advanced Administrator
Twitter: @GlynAtClosedWon
This was selected as the best answer
GlynAGlynA
If sunny.sfdc or I answered your question satisfactorily, please mark one of our replies as the "answer".  This will mark the post as "solved".  Thanks!

-Glyn
Jytohi PrakasJytohi Prakas
when we create a data in test class then list is empty when it is sorted by id, then how we gonna check it in test class?