liveBook · Manning

Early return

As explained in High Performance Unity Game Development

An early return is a control-flow technique in which a function exits before reaching its normal completion point.

An early return exits a function before its normal completion point. It can avoid work after a condition is met, but may make behavior harder to follow or skip important updates and cleanup. section 5.2.4 section 11.2

Choose where a check belongs by considering what the function promises to do:

  • In a game loop, returning when the game ends can skip later work, such as positioning enemies for the final screen. If that condition is rare, the return may offer no benefit. section 5.2.4
  • For enemy movement, check paralysis in the caller and keep moveEnemy focused on moving. Validate data at system boundaries, but avoid repeating known-validity checks in controlled hot code. section 11.2
Listing 11.6 Example with the branch moved out of moveEnemy()
void Tick(GameData gameData, float dt)
{
    for(int i = 0; i < gameData.AliveEnemyCount; i++)
    {
        int enemyIndex = gameData.AliveEnemyIndices[i];
        if(!gameData.EnemyParalyzed[enemyIndex]) #A
            moveEnemy(gameData, enemyIndex, dt);
    }
}

void moveEnemy(GameData gameData, int index, float dt)
{
    gameData.EnemyPosition[index] += 
        gameData.EnemyDirection[index] *
        gameData.EnemyVelocity * 
        dt;
}

See how the paralysis check moves out of moveEnemy() while the function retains its movement operation. section 11.2

How High Performance Unity Game Development covers it

How deep it goes
Contrast wrapped conditionals, early exits, and caller-side checks, then discuss skipped work and validation boundaries.
Examples
Illustrate a game-over return in Tick() and a paralysis check moved outside moveEnemy().
What it assumes
Assume responsibility for data created and passed within a controlled runtime loop, while validating data at external boundaries.
What you can do after
Evaluate whether a return is useful or risks skipping required updates, and decide whether a check belongs at a system boundary or caller.
How it connects
Tie early returns to conditional branches, input validation, and game-loop control flow.

Also explained in

Compare how 2 books explain early return →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of High Performance Unity Game Development. The section links point to the parts of the book it draws on.