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.
Define defensive programming in your own words, then walk through the concrete patterns you would actually apply in a real codebase to reduce production risk. For each pattern you name, explain how it prevents a specific class of production failure and give a short example of an outage it would have avoided.
Sample Answer
Direct answer
Defensive programming means writing code that assumes its inputs, callers, and environment will eventually misbehave, and that fails in a controlled, diagnosable way instead of silently corrupting state or crashing somewhere far from the actual mistake. The three patterns interviewers most want to hear are: guard clauses with fail-fast validation, fail-safe defaults, and circuit breakers.
Structured elaboration
Guard clauses and fail-fast validation. Check preconditions at the top of a function and return or throw immediately on invalid input, rather than nesting the happy path three levels deep inside conditionals. This prevents a class of bug where a function silently operates on partially-invalid data because the invalid case was never rejected, it was just never tested. The failure surfaces at the point of the bad input, with a clear message, instead of two call frames later as a confusing null pointer exception.
Fail-safe defaults. When a non-critical piece of configuration or a non-critical dependency is unavailable, degrade to a safe, conservative default rather than propagating the failure. A feature flag service that is down should default to the safest behavior (usually: feature off), not crash the request. This prevents an unrelated dependency's outage from becoming a full outage of your own service.
Circuit breakers. When a downstream dependency starts failing consistently, stop calling it for a cooldown window instead of retrying every request against a dependency that is already down. This prevents cascading failure: without a breaker, a slow or failing downstream call can pile up threads or connections in the caller until the caller itself falls over.
Worked example
Consider a checkout service that calls a fraud-scoring API before completing a purchase. Without defensive programming: the checkout handler passes the request straight to the fraud API, the fraud API starts timing out under load, checkout requests pile up waiting on the timeout, and the whole checkout service runs out of worker threads even though the actual defect is in the fraud API. With the three patterns applied: a guard clause rejects a checkout request with a missing user_id before it ever reaches the fraud API; if the fraud API is unavailable, a fail-safe default routes the order to manual review instead of blocking checkout entirely; and a circuit breaker stops calling the fraud API for 30 seconds once its failure rate crosses a threshold, so checkout degrades to manual review immediately instead of piling up timeouts. The outage that this avoids is a full checkout-service outage caused by a single downstream dependency, which is one of the most common real production incidents.
Trade-offs and pitfalls
Defensive checks are not free. Guard clauses that duplicate the same five checks in ten different functions become their own maintenance burden and are a sign you need a shared validator instead. Fail-safe defaults can hide a real problem if nobody monitors how often the default path is taken (a fraud check that silently defaults to manual review 40% of the time is itself an incident). Circuit breakers add a new failure mode of their own: badly tuned thresholds can trip on a brief blip and reject traffic the dependency could actually have served. The discipline is to add defensive checks at trust boundaries and for dependencies you do not control, not everywhere, and to monitor how often each defensive path actually fires.
Compare input-validation approaches for backend services: hand-rolled checks, JSON Schema, pydantic (Python), Joi (Node.js), and code-generated schemas (protobuf or Avro). Discuss how you would integrate validation into the controller layer, how you would map validation errors to HTTP responses, and how you would keep the validation rules maintainable as the schema evolves.
Sample Answer
Direct answer
Hand-rolled checks, JSON Schema, a runtime library like pydantic or Joi, and a code-generated schema from protobuf or Avro all solve the same problem at different points on a spectrum of how much structure you're willing to declare up front versus how much flexibility and directness you keep; the right choice depends mainly on how many fields you have, how often the schema changes, and whether validation needs to be shared across services or languages.
Structured elaboration
Hand-rolled checks. Direct, no dependency, and fastest to write for two or three fields, but the validation logic and its error messages live nowhere except inside the handler function, so they cannot be reused for a second endpoint with the same shape, and nobody can look at one file to see the whole contract.
pydantic (Python) / Joi (Node.js). A runtime library where you declare a schema once as code, and get back a validated, typed object (pydantic) or a validation result (Joi). This is a large step up for anything beyond a handful of fields: the schema is declarative, in one place, and testable in isolation from any specific route handler. The cost is a dependency, and in Python's case, a resulting object shape you may not fully control (though pydantic in particular has become close to a de facto standard for exactly this reason).
JSON Schema. A language-agnostic schema format that can be validated in almost any language and can also be used to auto-generate API documentation. It is more verbose to write by hand than pydantic or Joi's code-first schemas, and error messages from generic JSON Schema validators tend to be less friendly out of the box, but it is the right choice when the same schema must be validated by services written in different languages, or shared with API consumers as documentation.
Code-generated (protobuf, Avro). Here the schema is the source of truth and both the validation code and the language bindings are generated from it. This buys the strongest guarantee (the wire format and the in-code type are provably in sync, since they're generated from the same file) at the cost of a build step and a schema-evolution discipline (adding a field is easy, removing or renaming one is not).
Integrating into the controller layer. Regardless of which approach: validation should run as the very first thing in the controller, before any business logic executes, and it should map its failures into a single, consistent error-response shape (see a dedicated error-response-shape design) rather than letting each endpoint format its own ad hoc error body.
Worked example
A payments team starts with three hand-rolled if checks on a POST /charge endpoint. Six months later they have twelve endpoints each re-implementing similar amount/currency/customer-id checks slightly differently, and a bug slips through where one endpoint accepts a negative amount because its hand-rolled check used > 0 while another used >= 0. Migrating to a single pydantic model shared across all twelve endpoints (class ChargeRequest(BaseModel): amount: PositiveFloat; currency: constr(min_length=3, max_length=3); customer_id: str) collapses the inconsistency into one place: every endpoint either accepts a valid ChargeRequest or gets the same validation error shape, and the currency-length rule cannot silently drift between two files.
Trade-offs and pitfalls
The most common mistake is picking a heavier tool than the problem needs: introducing protobuf-generated validation for an internal endpoint with three fields that will never be called from another language adds a build pipeline for no real benefit. The opposite mistake is more damaging in practice: staying with hand-rolled checks well past the point where a shared schema library would have prevented cross-endpoint inconsistency, which is exactly the kind of subtle divergence bug that is hard to catch in code review because each individual check looks reasonable in isolation.
Suppose a profile-card component receives data from an unreliable API. List the concrete defensive checks you would add to avoid runtime errors and a poor user experience: null and undefined guards, default values, type narrowing in TypeScript, timeout handling, and retry limits. Show short code examples where helpful.
Sample Answer
Direct answer
A component receiving data from an unreliable API should treat every prop as potentially absent, malformed, or delayed, and should render a sensible, non-crashing result in every one of those cases rather than assuming the happy-path shape the API is supposed to return will always be what actually arrives.
Structured elaboration
Null and undefined guards. Before accessing a nested field (user.address.city), guard each level that could realistically be missing, either with explicit checks or with optional chaining (user?.address?.city), rather than assuming the whole chain is always present because the API contract says it should be; API contracts are aspirational, actual responses under real network and backend conditions are what the component must survive.
Default values. Provide a sensible default for anything the UI needs to render even when the real value is missing (user.name ?? 'Unknown user'), so the component degrades to a slightly-less-informative but still-functional display rather than rendering undefined as literal text or throwing.
Type narrowing in TypeScript. Even with a typed API client, the actual runtime response can disagree with its declared type (a backend bug, a version mismatch between client and server); a component receiving any-typed or loosely-typed external data should narrow it with an actual runtime check (typeof, a type guard function) before trusting the type system's compile-time promise, since TypeScript's types provide zero runtime enforcement.
Timeout handling and retry limits. If the component itself is responsible for triggering the fetch (rather than receiving already-fetched data as a prop), it needs its own timeout so a hung request doesn't leave the UI in a permanent loading spinner, and a bounded retry count so a genuinely-down API doesn't retry forever, consuming resources and giving the user false hope that the data will eventually arrive.
Worked example
function ProfileCard({ user }: { user: Partial<User> | null | undefined }) {
if (!user) {
return <div className="profile-card profile-card--empty">Profile unavailable.</div>;
}
const displayName = user.name?.trim() || 'Unknown user';
const avatarUrl = typeof user.avatarUrl === 'string' ? user.avatarUrl : DEFAULT_AVATAR;
const city = user.address?.city ?? 'Location unknown';
return (
<div className="profile-card">
<img src={avatarUrl} alt={displayName} onError={(e) => { e.currentTarget.src = DEFAULT_AVATAR; }} />
<h3>{displayName}</h3>
<p>{city}</p>
</div>
);
}
Here, the component accepts user as possibly null, undefined, or a Partial<User> (any subset of fields present), rather than assuming a fully-populated User. user.name is guarded and falls back to a label rather than rendering blank or undefined. avatarUrl is checked at runtime with typeof, not just trusted from its declared type, and additionally has an onError handler on the <img> tag itself for the case where the URL is a well-formed string that nonetheless points to a broken or expired image, which a type check alone cannot catch.
Trade-offs and pitfalls
Guarding every single field defensively can make a component harder to read if applied uniformly regardless of how unreliable the actual data source is; the right calibration is to defend hardest at the boundary where genuinely-external, unreliable data enters (a prop populated directly from an API response) and to trust internal, already-validated data more, rather than re-guarding the same value at every level it's passed through inside your own component tree. A common mistake is guarding against a missing field but forgetting to guard against a field being present with the WRONG type (a name field that is technically present but is null rather than absent, or is an object instead of a string), which a naive if (!user.name) check would actually catch correctly in most falsy cases, but a naive typeof check alone would miss if null weren't specifically included in the guard.
Design a consistent error-response shape for your public HTTP APIs. Propose the fields you would include, for example code, message, details, correlationId, and docsUrl, and explain how you would map internal exceptions to this shape in the service layer. Include how you would version the shape, localize messages, and avoid leaking sensitive information.
Sample Answer
Direct answer
A consistent error-response shape gives every client one predictable structure to parse regardless of which endpoint or which failure occurred, typically a machine-readable code, a human-readable message, an optional details object for field-level validation errors, a correlationId for support and debugging, and a docsUrl pointing to more context, with internal exceptions mapped to this shape at the service boundary rather than serialized directly.
Structured elaboration
The fields and what each is for. code: a stable, machine-readable string ("validation_error", "not_found", "rate_limited") that client code can branch on programmatically, distinct from message, which is for humans and can change wording over time without breaking a client's logic. message: a human-readable, localizable description. details: an optional structured object, most useful for validation errors, listing which specific fields failed and why (see the nested-payload validation pattern for its shape). correlationId: a value tying this specific error instance back to the full internal logs, letting support investigate without the client needing to describe what happened. docsUrl: an optional link to documentation for this specific error code, useful for a public API's client developers debugging an integration.
Mapping internal exceptions to this shape. A single, centralized error-handling middleware (rather than each route handler doing its own formatting) catches every exception that reaches the API boundary, looks up the appropriate code and HTTP status for its type, and serializes exactly this shape. Any exception type not explicitly recognized falls through to a generic internal_error code and a 500, with full detail logged internally but never included in the response body.
Versioning the shape itself. If the shape needs to change (adding a new required field, changing what code values exist), that change should go through the same versioning discipline as the rest of the API: additive changes (a new optional field) are safe to ship at any time, but changing the meaning of an existing code value, or removing one, needs to go through a new API version, since existing client code may already branch on the current code values.
Localizing message. Since code is what client code should branch on, message is free to be localized based on the client's Accept-Language header without breaking any client logic that correctly relies on code instead of parsing the message text, which is precisely the reason to keep those two concerns separate rather than have clients pattern-match on message strings.
Avoiding leaked information. No field in this shape should ever include a raw stack trace, an internal service name, a database error string, or any other implementation detail regardless of environment. That detail belongs in the internal logs, tied together with the same correlationId, never in the response body itself, even in development or staging environments, since a habit formed in one environment tends to leak into the others.
Worked example
A client sends a request with an invalid email field and a duplicate username. The centralized error middleware catches the underlying ValidationError raised by the service layer and returns:
{
"code": "validation_error",
"message": "The request could not be processed because one or more fields were invalid.",
"details": [
{"field": "email", "reason": "must be a valid email address"},
{"field": "username", "reason": "already taken"}
],
"correlationId": "c-8f21a",
"docsUrl": "https://api.example.com/docs/errors/validation_error"
}
A client library can branch on code === "validation_error" to show a form-validation UI, and iterate details to highlight the two specific fields, without ever needing to parse the English-language message text, which is free to be localized to the client's language without breaking that logic.
Trade-offs and pitfalls
The most common mistake is inventing a new code value ad hoc in a new route handler instead of reusing an existing one from a shared, documented list, which fragments the contract over time until clients can no longer rely on a finite, known set of codes. A second common mistake is putting genuinely useful debugging information (which validation rule failed, which field) only in message as free text, rather than in the structured details field, which forces client code to parse English sentences to extract information that should have been structured data from the start.
An API your frontend relies on changed its response shape unexpectedly. Describe strategies to handle API contract mismatches robustly on the frontend: runtime schema validation (for example with zod or io-ts), defensive parsing, feature detection and fallbacks, graceful-degradation UIs, and observability to surface the mismatch. Discuss the trade-offs between runtime guards and strict compile-time types, and how you would coordinate the fix with the backend team.
Sample Answer
Direct answer
When an upstream API changes its response shape unexpectedly, the frontend needs to detect the mismatch at runtime (not just trust its compile-time types), fail gracefully into a degraded but still-usable UI state rather than crashing, and surface the mismatch to observability so the team learns about the drift quickly rather than from a user complaint days later.
Structured elaboration
Runtime schema validation. A library like zod or io-ts validates the actual shape of an API response at the moment it arrives, distinct from TypeScript's compile-time types, which provide no protection whatsoever against a response that no longer matches what the type declares; parsing every external response through a runtime schema (UserSchema.parse(response)) means a shape mismatch is caught immediately, at the boundary, with a specific error identifying which field was unexpected, rather than surfacing later as a confusing crash deep inside a component that assumed a field existed.
Defensive parsing and fallbacks. Where a field is optional or was recently added to the API and might not yet be present in all responses (during a rollout, for example), defensive parsing accepts its absence and substitutes a sensible default rather than treating every deviation as a hard failure; this needs to be a deliberate choice, since a runtime schema validator can be configured either to reject any unrecognized shape strictly or to accept a superset and log what it didn't expect, and the right choice differs by field.
Feature detection over version checking. Where possible, check for the actual presence of a field or capability the code needs (if (response.newField !== undefined)) rather than trying to detect which "API version" produced this response, since feature detection degrades more gracefully as the API evolves incrementally and does not require the frontend to maintain a mapping of exactly which version introduced which field.
Graceful-degradation UI. When a validation failure does occur, the UI should fall back to a reduced but still-functional state (show what data IS available and valid, omit or placeholder what isn't) rather than a blank page or an uncaught-exception error boundary firing for what is really a data-contract problem, not a rendering bug.
Observability to surface the mismatch. Every runtime schema-validation failure should be logged to an error-tracking or monitoring system with the specific validation error (which field, what was expected versus received), tagged distinctly from other JavaScript errors, so the team notices a contract drift as an aggregate trend ("validation failures for field X started spiking at time Y") rather than discovering it from an isolated user bug report days later.
Coordinating with the backend team. A schema-drift monitoring signal is most useful when it is specifically actionable: routing it to the team that OWNS the API in question, ideally tied to their deploys, so a shape change introduced in a specific backend release can be traced back to that release quickly, rather than becoming a frontend-only investigation into a problem the frontend team cannot actually fix at its root.
Worked example
An API that used to return { user: { name, email } } changes, without notice, to { user: { name, email, verified } }, and separately, in a different deploy, silently starts returning email: null for a subset of enterprise accounts instead of a string. Runtime schema validation with zod, configured to accept unknown additional fields (.passthrough()), does not break on the new verified field appearing; the frontend simply ignores a field it doesn't yet use. The email: null change, however, DOES fail the schema (email: z.string()), which is caught immediately, logged to the error-tracking service tagged schema_validation_failure with the field name and account type, and the profile component renders with a degraded state ("Email unavailable") for that specific field rather than crashing the whole page. The logged event, filtered by account type, quickly surfaces that this is isolated to enterprise accounts, which is handed to the backend team as a specific, actionable report rather than a vague "something broke" ticket.
Trade-offs and pitfalls
Strict runtime validation that rejects ANY unrecognized field (rather than passing through additive changes) turns every routine, backward-compatible API addition into a frontend outage, which is usually the wrong default; the common mistake is configuring schema validation as strictly as possible "for safety" without considering that additive changes are supposed to be safe and should not trip the same alarm as a genuinely breaking change like a field changing type. The opposite mistake, validating nothing at runtime and trusting TypeScript's compile-time types alone, means a shape change surfaces as an uncaught runtime exception in whatever component first touches the missing or wrong-typed field, with no specific signal pointing at the actual API contract as the root cause.
Unlock Full Question Bank
Get access to all 32 Clean Code, Refactoring, and Maintainability interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.