Question About If Statements

Hello! I’ve just finished this course and thought it was great, I’m looking forward to going back and modifying the game to make sure I understand the concepts.

One question I’ve had throughout the course, you’ve been using the pattern

if (a != b) { return }
// desired code

rather than

if (a == b)
{
// desired code
}

This is different than the other courses I’ve taken through gamedev.tv. Is this generally just a personal preference thing, or does it have other implications? I personally find the method used in this course easier to parse, but am unsure if it’s appropriate to use as a widescale approach.

Thanks!

This is something that doesn’t have a one size fits all kind of answer. It really depends on the situation and the context of when you are using it.
For example lets say you have 2 variables, currentHealth and maxHealth and a bool called canHeal

for simplicity lets assume currentHealth will never be above max. with these 3 vars I’ll try to show you what I mean.

if(currentHealth == maxHealth)
{
    canHeal = false;
}

if(currentHealth != maxHealth)
{
    canHeal = true;
}

As you can see both methods are viable it just depends on when and how you use it.
I hope this all makes sense, if not feel free to ask more questions :blush:

Hmm, thanks for the response, but my question isn’t so much about that as that this course tends to return out of Methods if the condition isn’t met vs. the other courses which tend to run the code if the condition is met. I grabbed a line of code from the course, I’ll try to better explain what I mean.

    // This course's method
    public override void OnStopClient()
    {
        if (!hasAuthority) { return; } // condition wasn't met so method is exited

        AuthorityOnUnitDespawned?.Invoke(this);
    }

    // Other courses tend to do it this way 
    public override void OnStopClient()
    {
        if (hasAuthority) 
        {
            AuthorityOnUnitDespawned?.Invoke(this); // condition was met so code is run
        }
    }

Does that make more sense? Thanks!

Hi there, this is definitely a preference situation. Since we are using a lot of authority checks, the structure of just exiting the method if we don’t meet the requirements works well for this course. It allows you to see all the checks at the top laid out nicely.

In this case whatever works best for your and is readable is probably a good option.

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

Privacy & Terms