No, absolutely not - because if acct is null, it won't even get to isEmpty... it will immediately throw a NullPointerException.
Your test should be:
if (acct != null && !acct.isEmpty())
Note the use of && here, rather than your || in the previous code; also note how in your previous code, your conditions were wrong anyway - even with && you would only have entered the if body if acct was an empty string.
Alternatively, using Guava:
if (!Strings.isNullOrEmpty(acct))
Answer from Jon Skeet on Stack OverflowNo, absolutely not - because if acct is null, it won't even get to isEmpty... it will immediately throw a NullPointerException.
Your test should be:
if (acct != null && !acct.isEmpty())
Note the use of && here, rather than your || in the previous code; also note how in your previous code, your conditions were wrong anyway - even with && you would only have entered the if body if acct was an empty string.
Alternatively, using Guava:
if (!Strings.isNullOrEmpty(acct))
Use StringUtils.isEmpty instead, it will also check for null.
Examples are:
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
See more on official Documentation on String Utils.
You're trying to call the isEmpty() method on a null reference (as List test = null;). This will surely throw a NullPointerException. You should do if(test!=null) instead (checking for null first).
The method isEmpty() returns true, if an ArrayList object contains no elements; false otherwise (for that the List must first be instantiated that is in your case is null).
You may want to see this question.
I would recommend using Apache Commons Collections:
https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/CollectionUtils.html#isEmpty-java.util.Collection-
which implements it quite ok and well documented:
/**
* Null-safe check if the specified collection is empty.
* <p>
* Null returns true.
*
* @param coll the collection to check, may be null
* @return true if empty or null
* @since Commons Collections 3.2
*/
public static boolean isEmpty(Collection coll) {
return (coll == null || coll.isEmpty());
}
The empty string is a string with zero length. The null value is not having a string at all.
- The expression
s == nullwill returnfalseif s is an empty string. - The second version will throw a
NullPointerExceptionif the string is null.
Here's a table showing the differences:
+-------+-----------+----------------------+
| s | s == null | s.isEmpty() |
+-------+-----------+----------------------+
| null | true | NullPointerException |
| "" | false | true |
| "foo" | false | false |
+-------+-----------+----------------------+
Strings that have assigned with "", don't contain any value but are empty (length=0), Strings that are not instantiated are null.
I keep seeing list.size() > 0 in virtually every codebase that I've interacted with.
If you use list.size() > 0 instead of list.isEmpty(), could you explain why? is it habit or you didn't know isEmpty() existed?
Generally, your lists should always be initialized. One common misconception is that queries can produce a null list, which is never true.
For example, consider the following code:
Account[] records = [SELECT Id, Name, AccountNumber FROM Account];
if(records!=null && !records.isEmpty()) {
for(Account record: records) {
// Do Something Here
}
}
This is a waste of CPU time, because (a) records will never be null, and (b) iterating over an empty list is acceptable. Therefore, none of the three checks you might use are rarely appropriate. The only exception to this rule is when one query is used to fuel another query, in which case you would check for the presence of values before performing the query:
Account[] accounts = [SELECT Id, Name, AccountNumber FROM Account];
if(accounts.isEmpty()) {
return;
}
Contact[] contacts = [SELECT Id, Name, Email FROM Contact WHERE AccountId IN :accounts];
For lists you create yourself, you should always initialize them before using them. This is true for other types, like sets and maps, as well. There are, however, times when you'll need to check for a specific condition before using some lists. It helps if you experiment with the various types to get a feel for when you should be aware that a list may be null.
For example, consider a variable that binds to a multi-select picklist:
public String[] selectedValues { get; set; }
In this case, selectedValues will either be null, or will not be empty. You only ever need to check for != null in this case. Part of becoming an efficient developer is recognizing the patterns in a system. If you're still using myVar != null && !myVar.isEmpty() as a condition, that generally means you're making one or even two checks too many.
There is always one correct condition to use in every situation. If this isn't true, that suggests that values were not properly initialized elsewhere.
Edit: Safe Navigation Operator
As a special exception, you can now use the Safe Navigation Operator to skip the null check. That looks like this:
if(records?.size() > 0) {
/* Do something here */
}
Because of the changes brought in with the Safe Navigation Operator, when either size of the comparison is null, the result is false. If we want to abort early, then we can negate the entire thing:
if(!(records?.size() > 0)) {
return;
}
It is generally best to avoid null values in code so using null list references to indicate empty lists isn't usually good approach. That is this code:
List<String> strings = new List<String>();
...
for (String item : strings) {
...
}
is clearer and safer than this code:
List<String> strings = null;
...
if (strings != null) {
for (String item : strings) {
...
}
}
So prefer empty lists to null list references.
Personally I find myList.size() > 0 to be clearer than !myList.isEmpty() because the latter amounts to "not is empty" which takes a moment to understand. But as people will use both forms get used to both.
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;
Generally speaking, null values should be rare, and you should treat them as such. The results of a query always results in a list, even though it may be an empty list. Querying a checkbox field from the database will always be true or false, never null. Calling XmlNode.getChildElements() will never return null, but may return empty lists.
There are a few rare exceptions when you do need to check for null values. For example, when you make a variable transient, its not stored in the view state, so you usually need to implement lazy loading by checking for null first, and when you bind to a multi-select picklist, the list will always be either null or non-empty.
These are the exceptions to the rule, and you should learn them. Whenever you declare a list of your own, you should always assign a non-null value to it, which may be either a new list, or a list generated from a query. You should prefer to initialize those lists in a constructor, so that all your initialization code is in one place.
Generally speaking, when I use a method I'm not familiar with, I try calling it with a few different parameters to see if I can get a null value back instead of a list. I test it independently to verify its behavior. If it doesn't return a null, then I presume it never will. Just remember that most of the API avoids returning null values, or has a way to check beforehand. Most of the best design patterns for code avoid nulls using various techniques. As you gain experience, you'll learn those rare times when you must check for null, and find ways to code structures to reduce the null checks you need to make.