KatInterview

Defensive Coding: Validate and Harden a Snake Game

Data Structure DesignModel answer
MediumModel answerData Structure Designvalidationerror-handlingtesting

Last updated

Design an input-validation strategy, error-handling policy, and test suite to protect a Snake game implementation from every class of bad input.

Defensive Coding: Validate and Harden a Snake Game

You have just finished implementing a Snake game with the following interface:

SnakeGame(width, height, food)   # constructs the game
move(direction) -> int           # returns current score, or -1 on game over

The grid is width × height. The snake starts at (0, 0). The food list contains [row, col] positions that appear one at a time. move accepts a cardinal direction ("U", "D", "L", "R") and returns the current score, or -1 when the snake goes out of bounds or collides with itself.

Now think adversarially about your own code.

Your task:

  1. Identify every category of input or runtime scenario that could cause your implementation to produce a wrong answer, crash, or silently corrupt state.
  2. Propose a clear input-validation strategy and error-handling policy that distinguishes programmer/caller errors from legitimate game outcomes.
  3. List the subtle rule-ordering bugs that appear in otherwise-correct implementations.
  4. Provide a complete, working implementation with all defenses in place.
  5. Write a representative unit test suite covering each breaking category.
  6. Discuss the trade-offs between thorough defensive checks and runtime performance.

A strong answer explains why each check is placed where it is, not just what to check.

Hints

Hint 1

Separate concerns: inputs the caller controls (width, height, food, direction) are fundamentally different from game outcomes (wall hit, self-collision). These two categories deserve different handling mechanisms — don't conflate them.

Hint 2

The most common correctness bug has nothing to do with validation: it's the order in which you update the occupied set when the snake moves. Think carefully about whether the tail should be removed before or after you check for self-collision, and why eating changes that order.

Hint 3

Validate expensive things once at construction time so the hot path stays O(1). A move is called potentially thousands of times; a constructor is called once. Put the heavy lifting where it costs least.