Using variables just for assertions?

private void OnTriggerEnter2D(Collider2D other) {
        var health = GetComponent<Health>();
        Assert.IsNotNull(health, gameObject.name + ": No Health component");

        health.RemoveHealth(1);
    }

Should I be doing this? It trades a little efficiency for cleanliness. I’m wondering what other people do?

It’s a long and hoary debate and there is no right answer. Some people like to zealously guard every reference with a null check immediately before use. I think that tends to lead to messy code. Some people don’t check at all, leading to fragile code that fails spectacularly at the first sign of trouble.

Up to you to develop your own rule of thumb. Personally, if I expect something to be there always and have no fallback plan for if it is not, I let it crash. I will see that crash through various crash mechanisms, hopefully while still in testing, and adjust appropriately.

When you’re getting something from an external API, different rules and heuristics may apply, and it is up to you to read the API and understand when it may return a null.

Something to consider is Assert only does something if development build is specified.

I would consider using a classic null check. If something is unexpectedly null, you could log the message to a telemetry system, such as Unity Analytics. This will help you discover the issue in the wild and fix it in future builds.

Rule of thumb: Assert is for things that should never be null in practice. Null check is for things that might be null.

1 Like

@Mike01923 I had one more thought about this: far more useful to your engineering effort is to do EXACTLY like you did with lines 2 and 5 above: break out the health = GetComponent<>() from the use of health.

This is Very Good Practice™ from a code maintenance standpoint, and here’s why:

  • If you get a null reference and you have a chained-on single-statement nightmare (GetComponent.GetComponent.GetComponent type of constructs), you have no idea where things went bad when you’re looking at a crash report. If the software is out in the field, you can’t reason about it and won’t be able to pinpoint it until you do a refactor and software update and see the crash again in the wild.

Also,

  • Computers do one thing at a time, so this models what is actually happens

  • The compiler is going to make the same exact code, just as efficient.

2 Likes

2019.2 has added TryGetComponent

1 Like