Why we use "!damageDealer" and "return"?

I don’t understand why we are using “!damageDealer” and “return” in this case:

        DamageDealer damageDealer = other.GetComponent<DamageDealer>();
        if (!damageDealer) { return; }
        ProcessHit(damageDealer);

Instead of using more simple variant:

        DamageDealer damageDealer = other.GetComponent<DamageDealer>();
        if (damageDealer) { ProcessHit(damageDealer); }

Can anybody explain it to me?

Hi @PavelM,

Welcome to our community! :slight_smile:

return; terminates the method immediately. While your code is correct, it is not regarded as “simpler” but that’s a matter of habit. In this particular case, both variants are perfectly fine. However, if there was more code in the method block, many programmers would prefer the first variant because, for us humans, it translates to “if this is true, the rest is irrelevant. No need to read further”. No return; instruction indicates that there might be more code in the method block. We would have to skim the entire method block to see if the method executes any code if damageDealer was false.

void DoSomething()
{
    if (condition) { return;}

    if (condition2)
    {
        // code
    }
    // more code
}
void DoSomething()
{
    if (condition) {
       if (condition2)
       {
        // code
       }
       // more code
   }
}
void DoSomething()
{
    if (condition) {
       if (condition2)
       {
        // code
       }
   }

   //more code
}

Does that make sense?


See also:

Thank you for complete answer!
I’m a beginner, it’s complicated for me to understand sometimes. It makes sense in general, of course.

Don’t worry. If something is not clear, just ask. We are here to help. :slight_smile:

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

Privacy & Terms