General Question. Why? ! boolCodition {return}

Hi There,

Just want to say great work.

I have a general question. I often see programmers write such code as:

if (!playerCollider.IsTouchingLayers(LayerMask.GetMask(“Ground”)))
{
return;
}

Question. Why is it that programmers use " is not true" else return?

I would have personally wrote:

if (playerCollider.IsTouchingLayers(LayerMask.GetMask(“Ground”)))
{
//do magic :slight_smile:
}

Hope this makes sense.

1 Like

It’s simply to reduce the level of nesting and therefore indentation by bailing out of the function early. The idea is that excessive indentation makes code harder to read. It makes more sense if you have to repeat this check on several conditions, because your resulting “do magic” code is not indented:

    if (!foo) return;
    if (!bar) return;
    if (!baz) return;

    // do magic

Whereas with your style you’ll end up with a pyramid:

  if (foo)
  {
      if (bar)
      {
          if (baz)
          {
              // do magic
          }
      }
  }

Privacy & Terms