Say for example that I create a Duck
Duck myDuck = DuckFactory.CreateDuck();
In the past I've always check to see if myDuck is null
if (myDuck == null)
{
// Do stuff
}
I've recently looked at some code that check for null first.
if (null == myDuck)
{
// Do stuff
}
It seems to me that these are the same, but are there any differences between these two? Is there any performance benefits to one over the other? Is there a recommended best practice for checking if an object is null?
The best way is to only check when necessary. If your method is private , for example, so you know nobody else is using it, and you know you aren't passing in any nulls, then no point to check again. If your method is public though, who knows what users of your API will try and do, so better check.
isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list.
The second stems from C/C++ (and elsewhere) where this is a valid construct
if (myDuck = null) {
}
That's not valid in C# (unless your expression resolves to a boolean). For example, this is valid C#
bool b = ...
if (b = true) {
}
Putting the constant first was defensive to stop accidental assignment when you wanted comparison. I'd say more people put the variable to the left but there is nothing wrong with putting the constant to the left either.
Just pick one and be consistent about it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With