Is it bad practice to use return inside a void method?

Viewed 72535

Imagine the following code:

void DoThis()
{
    if (!isValid) return;

    DoThat();
}

void DoThat() {
    Console.WriteLine("DoThat()");
}

Is it OK to use a return inside a void method? Does it have any performance penalty? Or it would be better to write a code like this:

void DoThis()
{
    if (isValid)
    {
        DoThat();
    }
}
11 Answers

While using guards, make sure you follow certain guidelines to not confuse readers.

  • the function does one thing
  • guards are only introduced as the first logic in the function
  • the unnested part contains the function's core intent

Example

// guards point you to the core intent
void Remove(RayCastResult rayHit){

  if(rayHit== RayCastResult.Empty)
    return
    ;
  rayHit.Collider.Parent.Remove();
}

// no guards needed: function split into multiple cases
int WonOrLostMoney(int flaw)=>
  flaw==0 ? 100 :
  flaw<10 ? 30 :
  flaw<20 ? 0 :
  -20
;

Throw exception instead of returning nothing when object is null etc.

Your method expects object to be not null and is not the case so you should throw exception and let caller handle that.

But early return is not bad practice otherwise.

Related