Checking for Null - What Order

Checking for null - what order?

The second version ( null == str ) is called a yoda condition.

They both result in the same behavior, but the second one has one advantage: It prevents you from accidentally changing a variable, when you forget one =. In that case the compiler returns an error at that row and you're not left with some weird behavior of your code and the resulting debugging.

Is using the order of evaluation to check for null values bad practice?

No, it is perfectly fine and guaranteed to work in all cases.

Reference from Java specification: https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.7

Best way to check for null values in Java?

Method 4 is best.

if(foo != null && foo.bar()) {
someStuff();
}

will use short-circuit evaluation, meaning it ends if the first condition of a logical AND is false.

Does the order of checking whether a string is null or empty matter?

It's OK the way you did it, because the overload of == for System.String calls String.Equals, which allows nulls.

This is not universal, however: if you wanted to check string length instead of using == "", your first code snippet would be in trouble:

if(app.Logourl.Length == 0 || app.Logourl == null) // <<== Wrong!

while the second one would be fine:

if(app.Logourl == null || app.Logourl.Length == 0) // <<== Correct

The reason for this is short circuiting in the evaluation of || and && operators: once they know the result (true for ||, false for &&) they stop evaluation. In the second snippet above, if app.Logourl is null, the second half of the expression will be ignored, hence app.Logourl.Length would not throw a null reference exception.

Note: In recognition of checks like this happening all over the place, C# class library offers a convenience method for doing this check:

if (string.IsNullOrEmpty(app.Logourl)) {
...
}

Checking for empty or null Liststring

Try the following code:

 if ( (myList!= null) && (!myList.Any()) )
{
// Add new item
myList.Add("new item");
}

A late EDIT because for these checks I now like to use the following solution.
First, add a small reusable extension method called Safe():

public static class IEnumerableExtension
{
public static IEnumerable<T> Safe<T>(this IEnumerable<T> source)
{
if (source == null)
{
yield break;
}

foreach (var item in source)
{
yield return item;
}
}
}

And then, you can do the same like:

 if (!myList.Safe().Any())
{
// Add new item
myList.Add("new item");
}

I personally find this less verbose and easier to read. You can now safely access any collection without the need for a null check.

And another EDIT, which doesn't require an extension method, but uses the ? (Null-conditional) operator (C# 6.0):

if (!(myList?.Any() ?? false))
{
// Add new item
myList.Add("new item");
}

Testing for NULL in ORDER BY

When comparing with null you need the is operator.

SELECT * FROM tbl_name
ORDER BY CASE WHEN UpdatedDate is not null
THEN UpdatedDate
ELSE CreatedDate
END desc

or in your case you can just use

SELECT * 
FROM tbl_name
ORDER BY coalesce(UpdatedDate, CreatedDate) desc

Best practice to validate null and empty collection in Java

If you use the Apache Commons Collections library in your project, you may use the CollectionUtils.isEmpty and MapUtils.isEmpty() methods which respectively check if a collection or a map is empty or null (i.e. they are "null-safe").

The code behind these methods is more or less what user @icza has written in his answer.

Regardless of what you do, remember that the less code you write, the less code you need to test as the complexity of your code decreases.

Does the order matter when checking if a string isn't null and also isn't empty?

No, it doesn't matter in this case whether you check for empty or null first. You can use string.IsNullOrEmpty method instead and merge two conditions:

!string.IsNullOrEmpty(playerName) ? Hello " + playerName : "Hello Player 1!";

The order would matter if you were accessing a property of the string, for example:

if(playerName.Length < 10 && playerName != null)

This will fail if playerName is null because you are trying to access Length property on a null object. The correct way to check would be:

if(playerName != null && playerName.Length < 10)

Or you can shorten it using C#'s null-conditional operator:

if(playerName?.Length < 10)


Related Topics



Leave a reply



Submit