Clean Code, Refactoring, and Maintainability Questions
Writing code that other people can read, change, and keep alive over time: naming, function and module decomposition, avoiding duplication, readability, disciplined use of language idioms and design patterns, and recognizing code smells, extending into working effectively in large, aging, or unfamiliar codebases through safe incremental change, refactoring under test coverage, and managing technical debt. Covers both authoring professional-grade code beyond mere correctness and improving code you cannot rewrite without breaking it. Spans the coding-round quality signal and the seniority signal of leaving a codebase healthier than you found it.
A game occasionally fails to load textures or audio on low-memory devices, causing crashes or visual glitches. Propose a robust error-handling and recovery strategy for resource loading that preserves the user experience and makes debugging easier in production builds. Mention fallback policies, telemetry, and how you would test this behavior.
Sample Answer
Direct answer
When a texture or audio asset fails to load, most commonly on low-memory devices under real-world conditions, the game should substitute a lightweight placeholder immediately rather than crash or leave a visual gap, retry the real asset in the background if appropriate, and report the failure through telemetry so the team can see which assets and devices are actually affected without relying on player bug reports.
Structured elaboration
Fallback policy. Every asset load path needs a defined fallback asset (a low-resolution placeholder texture, silence or a minimal sound cue for audio) that is always available in memory or bundled with the app, so a failed load degrades visually or audibly rather than crashing the render pipeline or leaving an object with no texture at all, which on some engines can itself cause a crash or an undefined-behavior render state rather than simply looking wrong.
Retry strategy, tuned to the cause. A load failure caused by transient memory pressure (the OS reclaimed memory the game was using, common on mobile under multitasking) is often worth retrying once the memory pressure clears, whereas a load failure caused by a corrupted or missing asset file is not going to succeed on retry and should fall back permanently rather than retrying in a loop that wastes cycles and can itself contribute to further memory pressure.
Making this debuggable in production builds. A production build typically has no attached debugger and limited logging visibility, so the failure needs to be captured via telemetry: which specific asset failed to load, on which device model and OS version, at what point in the memory-pressure lifecycle, and whether the fallback was used or the load eventually succeeded on retry. Aggregated across all players, this turns "players on some devices see broken textures sometimes" into a specific, actionable signal ("asset X fails to load on 40% of attempts on device model Y specifically").
Preserving the user experience. The fallback should be visually or audibly unobtrusive rather than jarring: a low-res placeholder texture that still roughly matches the object's silhouette and color palette is much less noticeable than a bright pink "missing texture" placeholder or, worse, an invisible object; similarly for audio, a brief silence is usually less disruptive to the player than an abrupt, jarring alternate sound cue.
Worked example
A texture atlas fails to fully decompress on a low-memory Android device mid-gameplay. The asset-loading system catches the decode failure, immediately swaps in a pre-bundled low-resolution placeholder for the affected object so the frame renders without a gap or crash, logs a telemetry event (asset_load_failed, tagged with the asset ID, device model, available memory at time of failure, and "fallback_used: true"), and schedules one retry of the full-resolution asset after a short delay, on the theory that the memory pressure causing the initial failure may have been transient. If the retry also fails, the system does not retry further in a loop; it stays on the placeholder for the remainder of the session and logs that the retry also failed, which is a distinct, more concerning telemetry signal than a single transient failure that self-resolved.
Trade-offs and pitfalls
Retrying aggressively in a loop on a device that is genuinely, persistently memory-constrained can make the underlying memory pressure worse, competing with the game's own attempt to free memory elsewhere, which is why a bounded, single retry (or none, for a known-corrupted asset) is safer than an unbounded retry loop that optimistically assumes the condition will clear. A common mistake is designing a fallback asset that is visually jarring (bright, obviously-a-placeholder textures) specifically to make the bug easy to notice during development, and then shipping that same jarring placeholder to production, where it should instead be as visually unobtrusive as possible so a real player's experience degrades gracefully rather than looking broken.
What role do linters, formatters, and static analysis play in keeping a codebase clean? Name a couple of representative tools and explain the difference between what runs locally (pre-commit) versus in CI, and why that split exists.
Sample Answer
Direct answer. Linters catch style and correctness-adjacent issues mechanically and instantly (unused variables, obvious bugs, inconsistent formatting); static analysis goes deeper (type errors, security patterns, complexity thresholds) at a real but higher computational cost -- run the fast, cheap checks locally on every save/commit, and the slower, deeper ones in CI where a few extra minutes doesn't block a developer's flow.
The role each plays
- Formatters (Prettier, Black, gofmt): eliminate style debates entirely by making formatting a non-decision -- code is auto-formatted, so nobody reviews or argues about spacing/quote style ever again.
- Linters (ESLint, Pylint, golangci-lint): catch common bugs and style violations fast (unused imports, unreachable code, inconsistent naming) with sub-second feedback, ideal for real-time editor integration and pre-commit hooks.
- Static type checkers (mypy, TypeScript): catch a whole CLASS of bugs (wrong types passed, missing null checks) that a linter typically can't, at the cost of needing type annotations and somewhat longer analysis time.
- Deeper static analysis (security scanners, complexity/duplication analyzers): find subtler issues (SQL injection patterns, high-complexity functions) but can take minutes on a large codebase, so they belong in CI rather than blocking every keystroke.
Why the local-vs-CI split exists
A developer's moment-to-moment feedback loop needs to stay under roughly a second or people disable the tool out of frustration; anything slower belongs in a pre-commit hook (seconds) or CI (minutes), where the cost is amortized against a less time-sensitive point in the workflow. Putting a slow, deep security scan on every keystroke would make the editor unusable; putting NO fast checks locally means every trivial mistake only surfaces after a full CI run, wasting a much longer feedback cycle on something a formatter would have fixed instantly.
Trade-offs and pitfalls
- Running only in CI (nothing locally) means developers discover style/lint issues only after pushing, which is a slower and more frustrating feedback loop than catching them before commit -- invest in local tooling (editor integration, pre-commit hooks) even though it requires more per-developer setup.
- Don't let CI-only checks become 'optional' in practice by making them non-blocking; a security scanner that only warns and never blocks tends to get ignored over time once its warnings become background noise.
Describe defensive-programming patterns you apply when processing player input and external events in a game loop. Include at least three concrete practices that prevent crashes, exploits, or corrupted game state, while keeping responsiveness acceptable on constrained hardware.
Sample Answer
Direct answer
A game loop must treat player input and external events as untrusted and potentially malformed the same way a server treats a network request, because both crashes and exploits in games most often originate from an input or event the developer assumed could never happen, but that a real player, a malicious client, or an unreliable network connection eventually produces anyway.
Structured elaboration
Bounding and validating input values. Never assume an input value (a movement delta, an inventory index, a currency amount) falls within an expected range just because the UI normally prevents it from going out of range; a modified client, a race condition between two input events, or simply a numeric overflow from an unusually long play session can all produce an out-of-bounds value that the UI would never itself generate, and the game logic receiving that value needs to clamp or reject it explicitly, not trust that the sender-side UI already handled it.
Treating external events as untrusted, not just malformed local input. In a networked game, an event coming from another client (a move, an action, a chat message) must be validated server-side (or, for peer-to-peer, by every honest participant) exactly as strictly as local input, since a modified client can send literally anything over the wire regardless of what its own UI would normally allow; "the client already validated this" is never a safe assumption for anything gameplay-affecting or exploitable.
Rate limiting and debouncing. Processing every raw input event exactly as fast as it arrives can allow an exploit (rapid-fire input beyond what a human or the intended interaction rate should allow) or simply degrade performance under a flood of events (a network hiccup that delivers a backlog of queued events all at once); rate-limiting or debouncing certain input types protects both against exploitation and against a performance cliff from an unexpected event burst.
Keeping responsiveness acceptable on constrained hardware. These checks add real per-event cost, and on constrained hardware (older mobile devices, in particular) that cost is directly felt as input lag if applied carelessly; the discipline is to keep validation checks cheap (a numeric range check, a simple type check) and reserve anything more expensive (a full state-consistency check) for events that are inherently rarer (an inventory transaction) rather than events that fire every frame (a movement delta).
Worked example
A multiplayer game receives a "move to position" event from a client. Without validation: the server trusts the position outright and updates the player's location, which lets a modified client teleport anywhere on the map instantly by sending an arbitrary position, since nothing on the receiving end ever checked whether the move was physically possible given the time elapsed since the last known position. With defensive validation: the server computes the maximum distance the player could plausibly have covered in the elapsed time given their known movement speed, rejects (or clamps) any move exceeding that bound, and logs the rejection with the player ID and the attempted position for anti-cheat review, while a single accidental large jump from unusual network jitter is simply clamped to the plausible maximum rather than treated as a hard disconnect, since legitimate network jitter is common and should degrade gracefully rather than punishing an honest player for it.
Trade-offs and pitfalls
Validating every single per-frame input event with the same rigor as a rare, high-stakes event (an inventory trade, a purchase) adds real per-frame cost for comparatively little benefit, since most per-frame events (a movement delta within normal bounds) are low-stakes even if occasionally wrong; the right calibration is proportional to both the frequency of the event and the damage a malformed instance of it could do. A common and costly mistake is validating an event's TYPE and FORMAT (is this well-formed JSON, does it have the expected fields) while forgetting to validate its actual VALUE against game-state-derived bounds (is this specific move physically possible given the player's last known position and elapsed time), which is exactly the gap that lets an otherwise well-formed but game-breaking event through.
How do you decide between clearer, more readable code and a micro-optimized version, when a function runs extremely frequently (millions of times per second, or on a hot path)? What would make you accept the less-readable version, and what would you require alongside it if you did?
Sample Answer
Direct answer. Accept the less-readable version only when you have MEASURED evidence the hot path actually needs it (not a guess), and only alongside documentation, tests, and isolation that keep the cost contained to exactly that one function -- readability should be the default everywhere else in the same codebase.
What would make me accept the trade-off
- Profiling evidence, not intuition: a flamegraph or benchmark showing this specific function is a measurable bottleneck under realistic load, not a guess that 'this looks slow.'
- The gain is worth the readability cost: a 2x improvement on a function called millions of times per second matters; a 2x improvement on something called once a minute doesn't justify the trade at all, regardless of how 'hot' the code technically is.
- No simpler alternative gets you there: readability-preserving options (a better algorithm, caching, batching) have been considered and don't close the gap -- micro-optimization is the last resort, not the first idea.
What I'd require alongside the less-readable version
- A comment explaining WHY, with the profiling evidence referenced (a link to the benchmark or flamegraph), so a future reader doesn't 'clean up' the optimization back into the slower, clearer form without realizing why it exists.
- A test that pins the PERFORMANCE characteristic, not just correctness -- so a future change that silently reintroduces the slow path is caught, not just a change that breaks output.
- Isolation: the optimized code lives behind a clearly-named function/module boundary with a normal, readable interface, so the complexity is contained to one place rather than leaking into every caller.
- A note in the PR/commit explicitly flagging the trade-off for reviewers, so it's a deliberate, reviewed decision rather than something that slips through because 'the benchmark numbers looked good.'
A worked framing
Say a hashing function is called on every request in a load-balancer's hot path. Profiling shows a straightforward, readable implementation costs 40ns per call versus 8ns for a bit-twiddling optimized version, and this function alone accounts for 15% of total CPU under peak load. That's worth it: document the bit-twiddling with WHY, pin the benchmark in CI, and keep the optimized version behind a small, well-named function (fast_hash()) so callers still read cleanly.
Trade-offs and pitfalls
- The single most common mistake is skipping the measurement step and optimizing based on intuition -- many 'obviously slow' patterns turn out to be irrelevant to actual bottlenecks once profiled, and the readability cost was paid for nothing.
- Don't let one legitimately-optimized hot path set a PRECEDENT that spreads unmeasured 'clever' code elsewhere in the codebase under the banner of 'performance matters here too' -- keep the exception genuinely exceptional and visibly justified.
Compare dependency injection and the service-locator pattern. What do you gain and lose with each in terms of testability, discoverability of dependencies, and runtime cost, and which would you default to for a new module?
Sample Answer
Direct answer. Dependency injection gives you compile-time (or construction-time) visibility into what a class depends on and lets a test substitute a fake trivially; the service locator hides dependencies inside a global lookup, so a reader (and a test) can't tell what a class actually needs without reading its full body.
Dependency injection
class OrderService:
def __init__(self, payment_client, notifier):
self.payment_client = payment_client
self.notifier = notifier
Every dependency is visible in the constructor signature. A test constructs OrderService(fake_payment_client, fake_notifier) with zero global state to set up or tear down, and the signature itself documents the class's needs.
Service locator
class OrderService:
def charge(self, amount):
payment_client = ServiceLocator.get("payment_client") # dependency is hidden
payment_client.charge(amount)
A reader has to open the METHOD BODY (not just the constructor) to discover this class needs a payment client at all, and a test has to configure the global locator before running, then remember to reset it afterward or risk leaking state into the next test.
What you gain and lose with each
- Testability: DI wins clearly -- dependencies are explicit and swappable per-test with no shared global state. Service locator tests are more fragile (order-dependent, need setup/teardown discipline) because the locator itself is global mutable state.
- Discoverability: DI wins -- you can tell a class's dependencies from its constructor without reading every method. Service locator dependencies are invisible until you trace every call site that hits the locator.
- Runtime cost: essentially a wash for typical DI (constructor injection is just normal object construction); a poorly implemented service locator that does string-keyed lookups on every call adds a small runtime cost DI avoids, though a well-cached locator narrows this gap.
- Convenience for deep call chains: service locator can look more convenient when a dependency is needed 10 layers deep and you don't want to thread it through every intermediate constructor ('parameter drilling') -- but that's usually a signal the layering itself needs rethinking, not a case for hiding the dependency.
Default recommendation
Default to constructor-based DI for new code; it makes the dependency graph an explicit, reviewable part of the design and keeps tests simple and isolated. Reach for a locator (or a DI container that resolves dependencies FOR you, which is a more disciplined middle ground) mainly in frameworks/plugin systems where the set of implementations is genuinely dynamic and not known at construction time.
Trade-offs and pitfalls
- A DI container (Spring, Guice, etc.) can itself become a soft service locator if code reaches into the container directly at arbitrary points rather than only at composition roots -- the discipline that matters is WHERE resolution happens, not just which mechanism you use.
- Excessive constructor parameters from over-injecting is itself a smell (see the parameter-object survivor) -- if a class needs eight injected dependencies, that's often a sign it has too many responsibilities.
Unlock Full Question Bank
Get access to all 16 Clean Code, Refactoring, and Maintainability interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.