Hardening Stateful Grid Logic Against Malformed Inputs
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Prompt
Suppose you have just implemented a stateful grid-based engine—such as a SnakeGame(width, height, food) controller initialized with board dimensions and sequential target cells [row, col], where callers repeatedly invoke move(direction) to advance the snake and receive either the updated score or -1 on collision.
Walk through the adversarial inputs, boundary values, and multi-step execution hazards that could crash your class, corrupt its internal state, or silently compute wrong results, and explain how you would harden the code against them. Make sure you address missing or empty arguments, unrecognized step commands, ill-formed coordinate entries or target lists, off-board indices, fixed-width arithmetic overflow, and repeated or contradictory placement rules. Finally, lay out your boundary-validation architecture, your exception-versus-status error policy, an automated test plan spanning deterministic unit cases and randomized property-based suites, and how you balance runtime guardrails against hot-path latency in production.
Scope & Expectations
- Failure-mode taxonomy: Systematically catalog how types, shapes, index ranges, fixed-width cell math, mutable caller references, and subtle game-state transitions can go wrong.
- Boundary validation & error semantics: Define what gets checked and frozen on entry, and draw a crisp line between programmer contract violations and normal gameplay outcomes.
- Layered verification strategy: Combine targeted unit tests for known corner cases with randomized property-based, invariant, or reference-model checks that surface unexpected state bugs early.
- Production performance trade-offs: Quantify the cost of validation in hot loops versus entry boundaries, and explain which checks belong in production versus debug builds.
Step-by-step walkthrough
Pin down the API and its trust boundaries
Before hunting for bad inputs, draw the trust boundary—the dividing line between untrusted external callers and internal state that your own code controls:
Untrusted Caller / JSON Payload (width, height, food) (direction) | | ==========v==================v========== <- Trust Boundary (validate & copy ONCE) __init__(...) move(...) | | v v Internal State: self.width, self.height, self.food (immutable tuple), self.body (deque), self.occupied (set)Here is the public contract we are protecting:
class SnakeGame: def __init__(self, width: int, height: int, food: list) -> None: """Create a height x width grid (rows 0..height-1, cols 0..width-1). The snake starts at (0, 0) with length 1. food is a list of [row, col]; food[i] appears only after food[i - 1] is eaten.""" def move(self, direction: str) -> int: """Move one step in direction ("U", "D", "L", or "R"). Return current score (food eaten), or -1 if the snake hits a wall or itself. Once -1 is returned, the game is over and every later move returns -1."""Every code-breaking bug enters through one of three doors: constructor inputs,
moveinputs, or subtle interactions inside our own arithmetic and state updates.Catalog every category of code-breaking input
Walk systematically through each parameter and ask how type, shape, range, arithmetic, or domain rules can go wrong:
- Null, empty, or wrong-type dimensions (
width,height):- Zero or negative dimensions (
0,-5) leave the starting cell(0, 0)outside the board. - Wrong types such as
None,"10", or3.5. - Python's boolean trap: in Python,
boolis a subclass ofint, soisinstance(True, int)evaluates toTrueandTrue + 1 == 2! Without an explicitnot isinstance(x, bool)check,SnakeGame(True, 5, [])silently creates a 1-column board instead of failing.
- Zero or negative dimensions (
- Malformed or aliased
foodlists:food = Noneinstead of[], a bare coordinate[1, 2]instead of[[1, 2]], ragged items like[[1]]or[[1, 2, 3]], or JSON-decoded floats/strings like[[1.0, "2"]].- Caller aliasing (sharing a mutable list reference): if
__init__storesself.food = fooddirectly, the caller can runfood.append([-99, -99])mid-game and bypass constructor validation!
- Out-of-bounds coordinates and Python negative-index wraparound:
- Food at
[-1, 0]or[height, 0](off-by-one: valid rows are0throughheight - 1). - If the board is backed by a 2D Python list
gridand a bounds check only testsrow < height(forgetting0 <= row), moving up from row0producesrow = -1, andgrid[-1][col]silently wraps around to the bottom row instead of raisingIndexError!
- Food at
- Integer overflow across system boundaries:
- Python integers grow to arbitrary precision, so
row * width + colwill not overflow inside pure Python. However, integer overflow (when a number exceeds a fixed-width integer's maximum and wraps negative) strikes as soon as flat cell IDs touch a signed 32-bitint32(max2^31 - 1 = 2,147,483,647) in NumPy, C++/Java clients, or SQLINTcolumns:
- Python integers grow to arbitrary precision, so
Board size: 46,340 x 46,340 -> max ID = 2,147,395,599 <= 2,147,483,647 (fits in int32) Board size: 46,341 x 46,341 -> max ID = 2,147,488,280 > 2,147,483,647 (OVERFLOWS int32!) Board size: 50,000 x 50,000 -> max ID = 2,499,999,999 -> wraps in int32 to -1,794,967,297!- Duplicate or conflicting game constraints:
food[0] == [0, 0]spawns the first food directly under the snake's starting head.- Consecutive identical food
food[i] == food[i - 1]spawns the next food directly under the head at the exact instantfood[i - 1]is eaten. - Non-consecutive duplicate food (e.g.,
[[0, 1], [1, 1], [1, 0], [0, 0]]) may spawn on a cell currently covered by the snake's body—an ambiguous case whose behavior must be explicitly defined rather than left to chance.
- Invalid
movecalls and ordering bugs:- Bad directions:
None,"", lowercase"u","UP", or99. - Calling
move("R")after the game is already over (must stay-1, never resurrect the snake). - Tail-vacating order bug: moving the head into the exact cell the tail is simultaneously vacating (when not eating) is legal, so removing the old tail must happen before checking self-collision.
- Bad directions:
- Null, empty, or wrong-type dimensions (
Validate once at the boundary and freeze internal state
Apply fail-fast validation (checking inputs immediately upon entry and aborting before doing work) together with defensive copying (converting caller-owned mutable lists into private, immutable tuples). If any check fails, raise an exception before mutating or initializing half-built state:
from collections import deque DIRECTIONS = {"U": (-1, 0), "D": (1, 0), "L": (0, -1), "R": (0, 1)} # Cap total grid cells at INT32_MAX so flat cell IDs (row * width + col) never overflow 32-bit systems. MAX_CELLS = 2**31 - 1 def _require_int(name: str, value: object) -> int: # Reject bool explicitly because isinstance(True, int) is True in Python. if isinstance(value, bool) or not isinstance(value, int): raise TypeError(f"{name} must be an int, got {value!r}") return value def _parse_food(food: object, width: int, height: int) -> tuple: """Validate `food` once and return an immutable tuple of (row, col) pairs.""" if not isinstance(food, (list, tuple)): raise TypeError(f"food must be a list of [row, col] pairs, got {type(food).__name__}") parsed = [] for i, item in enumerate(food): if not isinstance(item, (list, tuple)): raise TypeError(f"food[{i}] must be a [row, col] sequence, got {item!r}") if len(item) != 2: raise ValueError(f"food[{i}] must have length 2, got length {len(item)}: {item!r}") row = _require_int(f"food[{i}][0]", item[0]) col = _require_int(f"food[{i}][1]", item[1]) if not (0 <= row < height and 0 <= col < width): raise ValueError(f"food[{i}] = ({row}, {col}) is outside {height}x{width} board") # Reject food spawning directly underneath the snake's head at t=0 or right upon eating. head_when_spawned = parsed[-1] if parsed else (0, 0) if (row, col) == head_when_spawned: raise ValueError(f"food[{i}] = ({row}, {col}) spawns directly under the snake's head") parsed.append((row, col)) return tuple(parsed) class SnakeGame: def __init__(self, width: int, height: int, food: list) -> None: _require_int("width", width) _require_int("height", height) if width < 1 or height < 1: raise ValueError(f"board must be at least 1x1, got {height}x{width}") if width * height > MAX_CELLS: raise ValueError(f"board size {height}x{width} = {width * height} exceeds {MAX_CELLS}") self.width = width self.height = height self.food = _parse_food(food, width, height) # immutable copy; caller mutations cannot affect us self.food_index = 0 self.body = deque([(0, 0)]) # body[0] is head, body[-1] is tail self.occupied = {(0, 0)} self.score = 0 self.over = FalseWhat about non-consecutive duplicate food that spawns while the snake's body still covers that cell? Because that depends on the player's future path, it cannot be rejected in
__init__. Instead, document a deterministic rule: the food waits on that cell and can only be eaten once the body vacates it; stepping onto that cell while the body (even the tail, since eating prevents the tail from moving!) still occupies it counts as a normal self-collision.Separate caller bugs from normal game outcomes
A clean error-handling policy never confuses programmer mistakes with normal domain events:
- Caller bugs raise specific exceptions: Raise
TypeErrorfor wrong types (None,3,True) andValueErrorfor invalid values ("u",width = 0, out-of-bounds coordinates), including the parameter name, offending index, and bad value in the message. Validate before changingself.body,self.score, orself.over, so a failed call is atomic (leaves the game untouched). - Normal game outcomes return values: Crashing into a wall or the snake's own body is part of playing Snake, so it returns
-1and setsself.over = True(sticky state: onceoverisTrue, future valid moves keep returning-1, though invalid directions like"u"still raiseValueError). Ifmove("u")returned-1instead of raising, a typo in client code would masquerade as a player losing the game! - Never silently "repair" bad inputs: Clamping
row = max(0, min(height - 1, row))or wrappingcol % widthhides real bugs behind plausible-looking wrong behavior. - Translate exceptions once at service edges: Inside core logic, let
TypeErrorandValueErrorpropagate; at an HTTP/RPC handler, catch them once and return400 Bad Requestwith the error message.
class SnakeGameValidated(SnakeGame): def move(self, direction: str) -> int: # 1. Validate caller input BEFORE reading or mutating game state. if not isinstance(direction, str): raise TypeError(f"direction must be a str, got {type(direction).__name__}") if direction not in DIRECTIONS: raise ValueError(f"direction must be one of 'U', 'D', 'L', 'R'; got {direction!r}") # 2. Sticky game-over state. if self.over: return -1 d_row, d_col = DIRECTIONS[direction] head_row, head_col = self.body[0] next_row, next_col = head_row + d_row, head_col + d_col # 3. Check both lower (0 <=) and upper (< limit) bounds explicitly. if not (0 <= next_row < self.height and 0 <= next_col < self.width): self.over = True return -1 next_cell = (next_row, next_col) eats = self.food_index < len(self.food) and self.food[self.food_index] == next_cell # 4. Remove vacating tail BEFORE checking self-collision (unless growing). if not eats: vacated_tail = self.body.pop() self.occupied.remove(vacated_tail) if next_cell in self.occupied: self.over = True return -1 self.body.appendleft(next_cell) self.occupied.add(next_cell) if eats: self.score += 1 self.food_index += 1 return self.score- Caller bugs raise specific exceptions: Raise
Catch known traps with targeted unit tests
Start with deterministic unit tests (fast, focused tests checking one specific input or scenario each). A parametrized test runs one test function across a table of failure rows so every item in our breaking-input catalog is locked down:
import pytest @pytest.mark.parametrize( "width, height, food, expected_exc", [ (0, 5, [], ValueError), # zero width (5, -1, [], ValueError), # negative height (3.5, 5, [], TypeError), # float width (True, 5, [], TypeError), # bool subclass-of-int trap (5, 5, None, TypeError), # null food list (5, 5, [[1]], ValueError), # malformed 1-element food entry (5, 5, [[1, 2, 3]], ValueError), # malformed 3-element food entry (5, 5, [[1.0, 2]], TypeError), # JSON float coordinate (5, 5, [[-1, 0]], ValueError), # negative row (Python wraparound trap) (5, 5, [[5, 0]], ValueError), # off-by-one row == height (5, 5, [[0, 0]], ValueError), # first food under starting head (5, 5, [[1, 1], [1, 1]], ValueError), # consecutive duplicate food (46_341, 46_341, [], ValueError), # cell IDs exceed signed 32-bit int max ], ) def test_init_rejects_invalid_inputs(width, height, food, expected_exc): with pytest.raises(expected_exc): SnakeGameValidated(width, height, food) @pytest.mark.parametrize("bad_dir", [None, "", "u", "UP", "X", 3, True]) def test_bad_direction_raises_without_corrupting_state(bad_dir): game = SnakeGameValidated(3, 3, [[0, 1]]) with pytest.raises((TypeError, ValueError)): game.move(bad_dir) # Game state must still be intact after the rejected call: assert game.move("R") == 1 def test_caller_mutating_food_list_after_init_has_no_effect(): caller_food = [[0, 1]] game = SnakeGameValidated(3, 3, caller_food) caller_food[0][0] = 999 caller_food.append([-5, -5]) assert game.move("R") == 1 def test_head_can_step_into_cell_tail_just_left(): game = SnakeGameValidated(2, 2, [[0, 1], [1, 1], [1, 0]]) assert [game.move("R"), game.move("D"), game.move("L")] == [1, 2, 3] # Snake of length 4 fills the 2x2 board; moving "U" steps onto (0, 0) as tail leaves (0, 0): assert game.move("U") == 3Catch unknown traps with property-based and differential tests
Unit tests only check examples you already thought of. Property-based testing (using a library like Hypothesis to generate hundreds of randomized inputs and automatically shrink any failing case down to the smallest reproducible example) catches subtle multi-step interactions using three techniques:
- Invariants (facts that must hold after every valid step): once
-1is returned, every later move returns-1; while alive,scoreincreases by0or1,len(body) == score + 1,len(occupied) == len(body), and every segment lies inside0 <= r < height, 0 <= c < width. - Differential testing (running the optimized
deque + setimplementation side by side against a dead-simpleReferenceSnakethat uses a plain Python list and asserting identical outputs on every move). - Smart input generation + fuzzing: if random food is scattered anywhere on the board, random walks almost never eat, leaving long-snake bugs untested! Placing generated food along the snake's walk grows the snake immediately—if someone checked
next_cell in self.occupiedbefore popping the tail, Hypothesis shrinks the failure down to a 2-cell board (width = 1, height = 2, food = [(1, 0)], moves = ["D", "U"]). Pair this with a fuzz test (feeding arbitrary random junk types into__init__) asserting that onlyTypeErrororValueErrorcan ever be raised, neverIndexError,KeyError, orAttributeError.
from hypothesis import given, settings, strategies as st STEPS = {"U": (-1, 0), "D": (1, 0), "L": (0, -1), "R": (0, 1)} class ReferenceSnake: """Tiny, obviously-correct list oracle used for differential testing.""" def __init__(self, width: int, height: int, food: list) -> None: self.width, self.height = width, height self.food = [tuple(cell) for cell in food] self.body = [(0, 0)] self.dead = False def move(self, direction: str) -> int: if self.dead: return -1 r, c = self.body[0][0] + STEPS[direction][0], self.body[0][1] + STEPS[direction][1] eaten = len(self.body) - 1 eats = eaten < len(self.food) and self.food[eaten] == (r, c) kept_body = self.body if eats else self.body[:-1] if not (0 <= r < self.height and 0 <= c < self.width) or (r, c) in kept_body: self.dead = True return -1 self.body = [(r, c)] + kept_body return len(self.body) - 1 @st.composite def reachable_games(draw): width = draw(st.integers(1, 6)) height = draw(st.integers(1, 6)) moves = draw(st.lists(st.sampled_from("UDLR"), max_size=40)) food, r, c = [], 0, 0 for d in moves: r, c = r + STEPS[d][0], c + STEPS[d][1] if not (0 <= r < height and 0 <= c < width): break prev = food[-1] if food else (0, 0) if (r, c) != prev and draw(st.booleans()): food.append((r, c)) return width, height, food, moves @settings(max_examples=250) @given(reachable_games()) def test_differential_and_invariants(case): width, height, food, moves = case fast_game = SnakeGameValidated(width, height, [list(cell) for cell in food]) ref_game = ReferenceSnake(width, height, food) prev_score = 0 for d in moves: got = fast_game.move(d) assert got == ref_game.move(d) if prev_score == -1: assert got == -1 elif got != -1: assert got in (prev_score, prev_score + 1) assert len(fast_game.body) == len(fast_game.occupied) == got + 1 prev_score = got junk = st.one_of( st.none(), st.booleans(), st.integers(-3, 10), st.floats(), st.text(max_size=3), st.lists(st.one_of(st.integers(-3, 10), st.floats(), st.none()), max_size=3), ) @settings(max_examples=250) @given(junk, junk, st.one_of(junk, st.lists(junk, max_size=4))) def test_fuzz_constructor_only_raises_documented_errors(width, height, food): try: SnakeGameValidated(width, height, food) except (TypeError, ValueError): pass- Invariants (facts that must hold after every valid step): once
Weigh defensive checks against production speed
Well-placed defensive checks cost almost nothing; poorly placed ones can turn an
O(1)operation intoO(N). Compare the numbers for a session ofM = 100,000moves withF = 10,000food items:Strategy A — Validate & freeze ONCE at the trust boundary (our design): __init__: validate 10,000 food items once = 10,000 checks move: 1 isinstance + 1 dict lookup * 100,000 = 100,000 O(1) checks Total work: ~1.1 * 10^5 simple steps (~10 ms in Python) Strategy B — Re-validate food & scan body invariants inside every move(): move: 10,000 food checks * 100,000 moves = 1,000,000,000 checks! Total work: 10^9 steps (~minutes in Python — 10,000x slower!)Use four practical rules in production code:
- Validate at trust boundaries, trust internal helpers: Public constructors, API endpoints, and file/JSON parsers validate strictly and normalize data into immutable types; private methods (
_step(...)) assume already-validated preconditions. - Never use
assertto validate external input: Running Python with optimization enabled (python -O) strips everyassertstatement out of the bytecode! Reserveassert(or aif DEBUG:flag enabled in CI and staging) strictly for internal invariants likeassert len(self.body) == len(self.occupied). - Validate batches outside hot inner loops: In numerical or ML pipelines (NumPy/PyTorch), check shape, dtype, and
isnanonce on the whole tensor at entry rather than branching inside a per-element loop. - Profile before removing cheap
O(1)checks: A singleisinstance+ dictionary lookup inmove()takes nanoseconds—keep cheap boundary checks unless profiling proves they sit on a true bottleneck.
- Validate at trust boundaries, trust internal helpers: Public constructors, API endpoints, and file/JSON parsers validate strictly and normalize data into immutable types; private methods (
Intuition & how it works
Think of input validation like airport security: you inspect tickets, bag dimensions, and prohibited items once at the entrance gate (the trust boundary, where untrusted external callers hand data to your code) and place cleared items into tamper-proof bins, so staff inside the terminal can work at full speed without re-searching bags at every hallway corner.
Without strict checks at the entrance, malformed inputs slip deep into internal logic and cause three kinds of failure: mysterious crashes far from the real bug, half-mutated state after an exception, or silent wrong answers—such as Python's isinstance(True, int) treating True as 1, or grid[-1][0] wrapping off the top edge of a board onto the bottom row. On the flip side, re-validating entire lists or copying data structures on every single method call turns fast O(1) operations into O(N) bottlenecks. The winning engineering pattern combines fail-fast validation (rejecting bad inputs immediately before changing any state), defensive copying (freezing mutable caller lists into private immutable tuples), clear separation between caller exceptions (TypeError / ValueError) and normal domain outcomes (-1 for game over), and layered unit + property-based tests (automated randomized tests that check universal rules and shrink failures to minimal examples).
Trace four calls against our hardened SnakeGame(width, height, food) to see each rule in action:
1. SnakeGame(True, 5, []) immediately raises TypeError("width must be an int, got True") before allocating any game state.
2. SnakeGame(5, 5, [[-1, 0]]) raises ValueError up front instead of letting row -1 wrap silently to row 4.
3. Calling game.move("u") during an active game raises ValueError before touching body or over, so a caller typo neither corrupts the board nor looks like hitting a wall.
4. Calling game.move("U") from (0, 0) cleanly hits the top wall, sets the sticky state self.over = True (a terminal flag that never resets), and returns the normal game outcome -1.
Key points
- Audit every entry point systematically: Check constructor arguments, method arguments, and deserialized payloads across six axes—null/empty values, wrong types (
boolvsint, floats from JSON), structural shape, index bounds (0 <= idx < limit), fixed-width integer overflow (e.g., flat cell IDsrow * width + colexceed signed 32-bit2^31 - 1 = 2,147,483,647starting at46,341 x 46,341), and conflicting domain rules (food[0]at(0, 0)or consecutive identical food). - Validate once at the trust boundary and freeze state: Convert mutable caller inputs like
food: list[list[int]]into an immutabletuple[tuple[int, int], ...]in__init__so external mutations (caller_food.append(...)) can never corrupt live state andmove()never has to re-scanfood. - Distinguish caller bugs from domain outcomes: Caller contract violations raise
TypeErrororValueErroratomically (before mutating fields), whereas valid moves that lose the game return-1. - Resolve ambiguous edge specifications explicitly: Decide and document what happens when valid inputs interact awkwardly at runtime—such as removing the vacating tail before checking self-collision so the snake can legally chase its own tail, or defining how non-consecutive repeated food behaves when covered by the snake's body.
- Layer unit, differential, and fuzz tests: Pair a parametrized unit-test table (one row per known bad input) with differential testing (comparing every move of the fast
O(1)implementation against a dead-simple list reference model on path-guided random inputs) and fuzzing (ensuring random junk raises only documentedTypeError/ValueError). - Keep
O(N)checks out of hot loops, and never guard inputs withassert: Validating10,000food items once plus100,000O(1)moves does~1.1 * 10^5checks, whereas re-checkingfoodinsidemove()does10^9checks (10,000xslower). Never use Python'sassertfor user input becausepython -Odeletes everyassertat bytecode compile time.
Common mistakes
- Relying on
isinstance(x, int)alone in Python: Becauseboolinherits fromint,TrueandFalsepass as1and0unless you explicitly rejectisinstance(x, bool). - Checking only upper bounds (
row < height): In Python, negative indices likegrid[-1][col]are valid list lookups that silently read from the end of the array instead of raising an out-of-bounds error. - Silently clamping or wrapping invalid inputs: Turning
row = -3into0orcol % widthhides caller bugs behind plausible-looking wrong state that is painful to debug in production. - Returning
-1for invalid directions likemove("u"): Collapsing programmer typos into the same return code as "snake hit a wall" masks broken client code as normal gameplay. - Mutating object state before validation finishes: Updating
self.scoreor poppingself.bodybefore checking arguments leaves a corrupted object if an exception is thrown mid-method. - Writing naive random generators in property tests: Placing food uniformly at random on a grid means a random-walk snake almost never eats, completely missing bugs that require length
>= 2(such as tail-collision ordering).
Follow-up questions
- When a caller passes an unrecognized movement string to
move(), why should the method raise an exception rather than returning the game-over code-1? It should raiseTypeErrororValueError, because-1carries a specific domain meaning ("the snake collided and the match ended") that callers act upon—such as closing a game session and recording a final score. Returning-1on"u"orNoneturns a client bug into a fake player loss. If raw user keystrokes can contain unmapped keys, filter or map them in the UI input layer before calling the engine's strictmove()API. - How does your validation architecture evolve when game setup and move commands arrive as untrusted JSON payloads over an HTTP endpoint? Validate in two layers at the API gateway/handler: first run a strict schema validator (such as JSON Schema or Pydantic with
ConfigDict(strict=True)so"3",3.0, andtrueare not silently coerced into integers) together with payload size caps (maximumwidth,height, andlen(food)so a10^7-item JSON array cannot trigger an out-of-memory denial of service). Then invoke the domain constructor and map anyTypeErrororValueErrorin one central exception handler to an HTTP400 Bad Requestresponse naming the exact field path (e.g.,food[2][0]). - Why can 100% line coverage still miss input-handling bugs, and how would you verify that your test suite genuinely catches broken guards? Line coverage only proves a line executed, not that your assertions would fail if that line were wrong. Use mutation testing (deliberately injecting small faults—by hand or with a tool like
mutmut—such as deletingnot isinstance(value, bool), changing0 <= rowtorow < height, or moving tail removal after the collision check) and verify that every single mutated version causes at least one unit or property test to fail.
Follow-up questions
- When a caller passes an unrecognized movement string to `move()`, why should the method raise an exception rather than returning the game-over code `-1`?
- How does your validation architecture evolve when game setup and move commands arrive as untrusted JSON payloads over an HTTP endpoint?
- Why can 100% line coverage still miss input-handling bugs, and how would you verify that your test suite genuinely catches broken guards?
Similar questions
- Node Value Spanning the Most Tree Depths
- Dynamic Integer Stream Median
- Minimum Slots for Cooldown Task Scheduling
- Kubernetes Crash Triage, Health Probes, and Python ETL Review
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger