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!