Code Quality, Error Handling, and Defensive Programming Questions
Writing robust, high-quality code that fails safely. Covers defensive programming, input validation, error handling and fault tolerance, logging for diagnosability, and general engineering-quality standards. Includes anticipating failure modes and making code resilient to bad inputs and unexpected states.
Describe the role of assertions and invariants in maintaining code correctness. When should assertions be used versus throwing exceptions? Provide an example where an assertion detects a developer error early and avoids a costly runtime check in production, and describe how this maps to design-by-contract thinking (preconditions, postconditions, invariants).
Sample Answer
Direct answer
An assertion checks a condition that your own code's logic guarantees should always be true if nothing upstream has a bug; an exception handles a condition that the outside world (a user, a file system, a network) can legitimately produce regardless of whether your code is correct. Assertions catch developer errors early and cheaply; exceptions handle the world being unpredictable.
Structured elaboration
What an assertion is for. An assertion encodes an invariant: a statement that, given correct code, must hold at this point in the program no matter what valid input arrives. If it fails, the bug is in the code that led to this point, not in the input or the environment. Because of this, assertions are cheap to reason about (you never need a recovery path for them, the correct response to a failed assertion is to fix the bug) and, in several languages, can be compiled out entirely in optimized production builds, which is precisely why they must never be relied on for something the outside world can trigger.
What an exception is for. An exception handles a condition that is a normal, expected possibility given a correct program: a file that does not exist, a network call that times out, a user who submits invalid input. These require an actual recovery path (retry, a default, informing the user) because they will happen in production no matter how correct the code is.
Preconditions, postconditions, and invariants (design by contract). A precondition is what a function requires to be true of its inputs to behave correctly; a postcondition is what it guarantees to be true of its output if the precondition held; an invariant is a condition that must hold at every observable point in an object's lifetime. Assertions are the natural implementation mechanism for all three inside a single codebase's own internal logic: asserting a precondition at function entry catches a caller who violated the contract due to a bug in their own code, which is different from validating an input that arrived from outside the trust boundary and might be malformed for entirely legitimate reasons.
The line between the two. The test is not "is this input bad", it's "could this input be bad even if every line of my own code is correct". A negative array length passed internally between two functions you wrote and control, where nothing external can produce that value if your code is right, is an assertion case. A negative quantity field parsed from a JSON request body is an exception (or validation-error) case, because a malicious or buggy client can produce it no matter how correct your server code is.
Worked example
A function withdraw(account, amount) internal to a ledger system might assert assert account.balance >= 0, "invariant violated: account balance went negative" right after debiting, because if the debit logic is correct, the balance should never go negative; if this assertion fires, there's a bug in the debit logic itself, and the fix is to find that bug, not to add a check that reacts gracefully to a negative balance in production. Contrast this with the same function's very first line, which must instead RAISE an exception (not assert) if the caller passes a negative amount: a negative withdrawal amount is exactly the kind of thing an upstream caller (a request handler parsing user input) can produce, whether or not the ledger's own internal logic has any bugs at all, so it needs a real, always-active check, and the right response is to reject the request, not to crash a debug build's assertion and silently no-op in production.
Trade-offs and pitfalls
The most costly mistake is using an assertion to validate something a real caller can trigger: because assertions can be disabled in optimized builds in several languages (C's NDEBUG, Python's -O flag), a check that only exists as an assertion can silently vanish in production, meaning the exact case it was meant to guard against reaches production code entirely unchecked. The opposite mistake, wrapping every internal invariant in a full exception with a try/catch elsewhere in the codebase, adds real performance and readability cost for something that, if your own code is correct, should genuinely never happen and does not need a recovery path at all, only a way to fail loudly and immediately during development and testing.
You are implementing a high-performance financial aggregation in C++ that sums millions of int64 values. Describe strategies to avoid overflow and preserve precision over large sums: a wider accumulator, periodic reduction, compensated summation (Kahan summation), and a big-integer fallback. Discuss the performance-versus-correctness trade-offs of each.
Sample Answer
Direct answer
Summing millions of floating-point values with a naive running total accumulates rounding error that grows with the number of additions, and can become catastrophically wrong once the accumulator itself becomes large relative to the individual values being added; Kahan summation tracks and corrects for the specific rounding error lost at each step, recovering close to exact precision at a small, constant extra cost per addition.
Structured elaboration
Why naive summation degrades. Each floating-point addition rounds its result to the nearest representable value; when the running total is already large and you add a comparatively small value, the low-order bits of that small value can be entirely lost in the rounding, contributing nothing to the total even though mathematically it should. Summed over millions of additions, this isn't a one-time rounding of the final answer, it's a compounding loss that grows with the number of terms and with how large the accumulator becomes relative to the values still being added.
A wider accumulator (e.g., summing into a double when inputs are float, or an extended-precision type). This delays the point at which the accumulator becomes "too large relative to the next value" by giving more bits of precision to work with, but does not eliminate the underlying problem, only pushes it further out; for a genuinely large enough sum, even a wider accumulator eventually exhibits the same degradation.
Periodic reduction (pairwise/hierarchical summation). Rather than one long running total, sum values in a tree (pairs, then pairs of pairs, and so on): this keeps each individual addition's two operands closer in magnitude to each other for longer, which is specifically what limits how much low-order precision gets lost at each step, and is a common approach in numerical libraries for exactly this reason.
Kahan (compensated) summation. Maintains a separate "compensation" value tracking the error lost in each addition's rounding, and feeds that error back into the NEXT addition to correct for it; this recovers close to exact precision using only a small, fixed amount of extra arithmetic per addition (a few extra operations per element), regardless of how many elements there are, which makes it strictly better than a wider accumulator alone for a sum where this class of error genuinely matters.
Big-integer fallback. For a sum where inputs are actually fixed-point or integer-representable quantities (a financial ledger's cent amounts, for instance) rather than genuinely continuous floating-point measurements, the more robust fix is often to avoid floating point ENTIRELY and sum as integers or a fixed-point/decimal type, sidestepping the rounding-error problem altogether rather than mitigating it.
Performance versus correctness. Kahan summation costs roughly four floating-point operations per element instead of one, a real but usually acceptable overhead for a batch aggregation that runs periodically rather than in an extremely tight, latency-critical hot loop; for a genuinely latency-critical inner loop where this precision doesn't actually matter to the business outcome, plain summation with a wider accumulator may be an acceptable, cheaper trade.
Worked example
double kahan_sum(const std::vector<double>& xs) {
double sum = 0.0, c = 0.0;
for (double x : xs) {
double y = x - c;
double t = sum + y;
c = (t - sum) - y;
sum = t;
}
return sum;
}
Executed and verified (g++, deliberately adversarial test case): summing a vector containing one value of 1.0e16, followed by 100,000 individual values of 1.0, followed by -1.0e16 (a true mathematical total of exactly 100,000.0). Naive left-to-right summation produced 0 (the individual 1.0 additions were entirely lost against the 1.0e16 accumulator before the final subtraction, since each 1.0 addition rounds to no change at all against a value that large). Kahan summation, on the SAME input, produced exactly 100000, matching the true mathematical answer with zero measured error, against the naive approach's error of 100000 (its full expected value, since it produced 0 instead). This is a deliberately extreme case constructed to make the effect visible and unambiguous; real financial aggregations rarely hit this exact pathological shape, but the same directional bias (naive summation systematically losing low-order precision as the accumulator grows) is present at a smaller, harder-to-notice scale in any large real sum, which is precisely what makes it dangerous: it degrades silently rather than producing an obviously-wrong number.
Trade-offs and pitfalls
The naive-versus-Kahan comparison above is deliberately adversarial to make the failure obvious; the real risk in production is the opposite of obvious, a financial aggregation that's subtly, silently off by a small relative amount that doesn't trigger any alarm because the number still looks plausible. The most common mistake in practice is assuming a wider accumulator type (switching float to double) fully solves the problem, when it only raises the bar at which the same class of error reappears; for a sum whose scale is genuinely large enough, or whose correctness is high-stakes enough (a financial ledger, in particular), compensated summation or an exact fixed-point representation is the more robust fix, not simply a wider floating-point type.
Explain patterns for handling missing or null values in strongly-typed languages like Java and dynamically-typed languages like Python or JavaScript. Include examples of Option/Maybe-style types, exceptions, and sentinel values, and explain when you would use an assertion compared to throwing a recoverable error.
Sample Answer
Direct answer
Strongly-typed languages let you make "this can be absent" part of the type itself (an Optional, Maybe, or nullable type), which forces every caller to handle the absent case at compile time; dynamically-typed languages have no such enforcement, so the same discipline has to be applied by convention, through explicit checks, sentinel values, or exceptions, and it is far easier to forget.
Structured elaboration
Option/Maybe types (Java's Optional<T>, Kotlin's T?, Rust's Option<T>). These make "might not have a value" visible in the type signature itself. A function returning Optional<User> cannot be called and have its result used as a User without the caller explicitly unwrapping it (via .get(), .orElse(default), or a null check), so the compiler catches the case where a developer forgot that the value might be absent.
Sentinel values. A special value from within the same type used to mean "nothing" (returning -1 for an index not found, or an empty string). These predate Optional types and are still common, particularly in older or lower-level codebases, but they are a real hazard: a sentinel is indistinguishable from a legitimate value of the same type unless every caller remembers to check for it, and nothing enforces that they do. indexOf returning -1 is the classic example: if a caller forgets to check and uses the result directly as an array index, it silently wraps or throws far from the actual bug.
Exceptions. Appropriate when absence represents an actual error condition the caller must react to (a required config value is missing), not merely a normal possible outcome (a user has no middle name). Throwing for something that is a completely normal case forces every caller into try/catch for ordinary control flow, which is a sign the wrong tool was chosen.
Dynamically-typed languages (Python, JavaScript). There is no compiler to force a null check, so None/null/undefined handling depends entirely on discipline: explicit is not None checks at the boundary where a value enters the system, defensive defaults (value = data.get("key", default)), and, where the codebase uses type hints, tools like mypy can catch some cases statically even though the language itself does not enforce them at runtime.
Assertions versus recoverable errors. An assertion says "this should be logically impossible given my own code's invariants; if it happens, my code has a bug", and is appropriate for catching a developer error early (an internal invariant that should never be violated if the code upstream is correct). A recoverable error (an exception or an Optional/error-result) is for a condition that is possible in the outside world regardless of whether the code is correct (a user did not provide their middle name; a file does not exist). Do not use an assertion for something a real caller can legitimately trigger, since assertions can be stripped in optimized production builds in several languages and are not guaranteed to run.
Worked example
A Java method Optional<User> findById(String id) forces every caller to write findById(id).map(User::getName).orElse("unknown") or similar, and the compiler will not let a caller treat the return value as a bare User. The equivalent Python function find_by_id(user_id) might return None on a miss, and nothing stops a caller from writing find_by_id(user_id).name and getting an AttributeError: 'NoneType' object has no attribute 'name' at runtime, potentially in a code path that only executes rarely, long after the function was written and long after the original author has moved to another project.
Trade-offs and pitfalls
Overuse of Optional/Maybe wrapping for values that are realistically always present adds ceremony without benefit; reserve it for genuinely-optional data. The most damaging mistake in dynamically-typed languages specifically is treating None/null handling as optional discipline rather than a hard rule at every boundary where external data enters the system (an API response, a database read, a config file): that is precisely where a missing null-check turns into a production incident, because it is exactly the boundary where the type system (if any) has the least information about what's actually there.
You are developing firmware for an IoT device that sometimes loses power mid-write and ends up with corrupted state. Describe defensive strategies at the software and firmware level to ensure state consistency and recovery: journaling, atomic writes, checksums, transactional updates, wear-leveling, and graceful degradation for the case where the state cannot be repaired.
Sample Answer
Direct answer
An IoT device that can lose power mid-write needs its persistent state design to assume that ANY write can be interrupted at an arbitrary point, and to guarantee that after a power loss the device recovers to either the state before the write or the state after it, never a corrupted state in between; this is achieved through atomic writes, journaling, checksums, and a defined recovery procedure that runs on every boot.
Structured elaboration
Atomic writes. Never overwrite a live state file in place. Write the new state to a temporary location, then use a single atomic operation (a rename, on most embedded filesystems) to make it the active file; a power loss during the write leaves either the old file intact (rename never happened) or the new file fully intact (rename completed), never a half-written file masquerading as valid.
Journaling. Before making a change, write a small journal entry describing the intended change (a write-ahead log), then apply the change, then mark the journal entry complete. On boot, if an incomplete journal entry is found, the device can either replay it to completion or roll it back, rather than trusting whatever partial state exists on disk.
Checksums. Every persisted state block includes a checksum computed over its own contents. On boot, before trusting any stored state, recompute and compare the checksum; a mismatch means this block was only partially written before power was lost, and the device should fall back to its last known-good state (kept in a separate, previously-checksummed location) rather than trusting a block that failed its own integrity check.
Transactional updates. Where multiple related values must change together (updating both a counter and a corresponding flag), group them into a single atomic unit (write them as one block with one checksum, or use the journaling pattern above) rather than writing them as two separate operations, since a power loss between the two writes would otherwise leave them inconsistent with each other.
Wear-leveling. Flash storage has a limited number of write cycles per cell; spreading writes across the storage medium rather than always rewriting the same physical location extends the device's operational lifetime, and is usually handled by the flash translation layer or filesystem rather than application code, but application code should avoid patterns that defeat it, like writing extremely frequently to a fixed-size, unchanging file.
Graceful degradation when state cannot be repaired. If, after a checksum failure and a fallback to last-known-good state also fails (both copies corrupted, an unlikely but real scenario for a device that lost power during the write of BOTH), the device should fall back to a safe, known factory-default state rather than attempting to guess at a repair, and should surface this event clearly (a status flag, a log entry sent on next successful connectivity) so it is not silently operating on defaults indefinitely without anyone knowing.
Worked example
A smart thermostat storing its current schedule: instead of write(schedule_file, new_schedule) directly, the device writes new_schedule to schedule_file.tmp, computes and appends a checksum, then calls rename(schedule_file.tmp, schedule_file). If power is lost mid-write to .tmp, on reboot the device finds schedule_file unchanged (the rename never happened) and schedule_file.tmp incomplete or checksum-invalid, discards the .tmp file, and boots with the previous, still-valid schedule; the user loses only the update that was in progress, not the whole schedule. If power is lost DURING the rename itself (a much narrower window on most filesystems, since rename is designed to be atomic), the filesystem guarantees the rename either did or did not happen, never a partially-renamed file.
Trade-offs and pitfalls
Atomic-write-via-temp-file-and-rename assumes the underlying filesystem actually implements rename atomically, which is true for most embedded Linux filesystems but is a real assumption to verify for the specific hardware and filesystem in use, not something to take for granted. Checksums and journaling add both storage overhead and write amplification (more total bytes written per logical update), which directly interacts with the wear-leveling concern above; on a severely storage- or write-cycle-constrained device, this is a genuine engineering trade-off between corruption-safety and device lifetime that needs to be made deliberately, not defaulted into.
Implement bool add_will_overflow(int32_t a, int32_t b) in C++ that returns true if a + b would overflow a 32-bit signed integer. Do not use a 64-bit type. Include unit tests for edge cases such as INT_MAX + 0, INT_MAX + 1, and negative overflows, and explain your approach.
Sample Answer
Direct answer
Detecting whether a + b would overflow a 32-bit signed integer, without widening to 64 bits, means reasoning about the operation BEFORE it happens using only the bounds of int32_t itself: check whether b is positive and a is already close enough to the maximum that adding b would exceed it, and symmetrically for a negative b against the minimum.
Structured elaboration
Why you can't just compute a + b and check the result. Computing the sum first and then checking whether it looks wrong is undefined behavior for signed integer overflow in C++, meaning the compiler is permitted to assume overflow never happens and can optimize the check away entirely, silently producing incorrect results specifically in the case you were trying to detect. The check has to be done using only values that are guaranteed to be representable, before the actual addition occurs.
The two symmetric cases. If b is positive, overflow happens when a is already greater than INT32_MAX - b (equivalently, adding b would push past the maximum); this comparison, a > INT32_MAX - b, is always computable without overflow since INT32_MAX - b cannot itself overflow when b is positive. If b is negative, overflow (underflow past the minimum) happens when a is less than INT32_MIN - b; note INT32_MIN - b is safe to compute here specifically because b is negative, making this subtraction move away from, not toward, the boundary.
The zero and boundary cases. b == 0 never overflows regardless of a, and the two comparisons above naturally handle this correctly without a special case, since a > INT32_MAX - 0 is simply a > INT32_MAX, which is never true for a valid int32_t value of a.
Worked example
bool add_will_overflow(int32_t a, int32_t b) {
if (b > 0 && a > std::numeric_limits<int32_t>::max() - b) return true;
if (b < 0 && a < std::numeric_limits<int32_t>::min() - b) return true;
return false;
}
Executed and verified (g++, -Wall -Wextra): add_will_overflow(INT32_MAX, 0) is false (no overflow); add_will_overflow(INT32_MAX, 1) is true (the classic overflow case); add_will_overflow(INT32_MAX - 1, 1) is false (exactly at the boundary, still valid); add_will_overflow(INT32_MIN, -1) is true (the symmetric underflow case); add_will_overflow(INT32_MIN, 0) is false; add_will_overflow(INT32_MIN + 1, -1) is false (exactly at the boundary on the negative side); ordinary values like add_will_overflow(100, 200) and add_will_overflow(-100, -200) are both false; and add_will_overflow(INT32_MAX/2 + 1, INT32_MAX/2 + 1) is true, confirming the check also catches an overflow that occurs from two moderately-large positive values rather than only from a value already at the exact boundary.
Trade-offs and pitfalls
The single most common mistake is writing the intuitive-looking but broken version, int32_t sum = a + b; if (sum < a) return true; (checking whether the result "wrapped around" to something smaller than one of the inputs): this relies on signed overflow actually wrapping, which is undefined behavior in C++ and not guaranteed to behave that way at all, especially under compiler optimizations that are explicitly permitted to assume signed overflow never occurs and can eliminate the check entirely. A second, more subtle mistake is getting the comparison direction backwards for the negative-b case (checking a < INT32_MIN + b instead of a < INT32_MIN - b), which happens to work correctly by luck for some inputs and silently fails for others; testing both boundary directions explicitly, as in the worked example, is what catches this class of subtle sign error.
Unlock Full Question Bank
Get access to all 10 Code Quality, Error Handling, and Defensive Programming interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.