On checking for == null or != null

Hi,
I’m wondering if there’s maybe a principle I’m missing, oar which I can learn here.
I’m forever setting up my null reference safegurds ‘backwards’ to what Sam does. And I wondered if it’s genuinely a case of tomayyto vs tomahhhto, or there’s a principle I’m missing.

The example below, from my version of EnemyHealthDisplay.cs…

        private void Update()
        {
            targetHealth = playerFighter.GetTarget();
            if (targetHealth != null)
            {
                healthtext.text = String.Format("{0:0}%", targetHealth.GetPercentHealth().ToString());
            }
            else
            {
                healthtext.text = "N/A";
            }
        }

My code uses N/A as a catch-all and does not return early. Sam’s code inverts this. He checks for ==null, then does an early return.
Both function. But is there a hidden wisdom or efficiency in what Sam’s doing? I was thinking perhaps in the Update method, using an early return to exit the method could be (very slightly!) more performant than checking an extra condition, as my code does?
I’m just wondering, in case it may be important in more complex condition checks.
Thanks!

1 Like

It’s just a little more common to see null checks and return early in code.

It tends to allow you to not to need to indent an extra level, which usually makes code easier to read. But either way works.

1 Like

In terms of raw execution, there’s really no difference, a comparison is made, and a branch is selected. In terms of readability, that depends on what’s easiest for you to read. I tend to go with aborting early methods (if !), but neither is gospel.

thanks to you both! I couldn’t choose both responses as solutions, but they are!

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms