Programming Fundamentals Questions
Language-agnostic building blocks of writing code: variables, primitive and composite data types, scope and lifetime, functions and callbacks, control flow, and expressions versus statements. Covers the mental model a candidate needs before any language-specific or algorithmic depth. The baseline literacy layer of a technical screen.
Define the four pillars of object-oriented programming: encapsulation, abstraction, inheritance, and polymorphism. For each, give a short, concrete example in a language of your choice, explain one practical benefit it provides, and name one common pitfall or misuse you have seen.
Sample Answer
Direct answer
The four pillars are encapsulation (bundling data with the methods that operate on it, and hiding internal state behind a controlled interface), abstraction (exposing only what a caller needs, hiding how it's implemented), inheritance (a class reusing and specializing another class's behavior), and polymorphism (code that works against a common interface behaving correctly for many concrete types).
Structured elaboration
- Encapsulation: internal fields are kept private (or convention-marked, e.g. Python's leading underscore) and reached only through methods. Benefit: you can change the internal representation later without breaking every caller. Pitfall: exposing a mutable internal collection directly (a public list field) defeats encapsulation even if the field itself is 'private', because callers can still reach in and mutate it.
- Abstraction: a caller depends on a small, stable surface (an interface, an abstract base class, or just a documented method contract) rather than on implementation detail. Benefit: implementations can be swapped freely. Pitfall: a 'leaky abstraction' that forces callers to know implementation detail anyway (e.g. an interface that only makes sense if you know it's backed by a SQL table).
- Inheritance: a subclass gets a base class's fields and methods and can override behavior. Benefit: real code reuse for a genuine is-a relationship. Pitfall: inheritance used purely for code reuse (not a real is-a relationship) creates fragile coupling, since a change in the base class can silently break every subclass; composition (a class holding an instance of another class instead of inheriting from it) is often the safer default for anything beyond a shallow, genuinely-is-a hierarchy.
- Polymorphism: calling code written against a base type or interface automatically gets the right behavior for whatever concrete subtype is actually passed in, without an if/else on type. Benefit: adding a new type means adding a new class, not editing every call site (this is most of what the 'open/closed' principle (a design should be open to new behavior but closed to editing existing, working code) is about). Pitfall: relying on type-checking (
isinstance) instead of polymorphism reintroduces the very branching the pattern exists to remove.
Worked example
class MetricCollector:
def __init__(self, name):
self._name = name # encapsulation: internal state, reached via methods
self._samples = []
def record(self, value):
self._samples.append(value)
def summary(self):
return f"{self._name}: n={len(self._samples)}"
class LatencyCollector(MetricCollector): # inheritance
def summary(self): # polymorphism: overrides base behavior
if not self._samples:
return f"{self._name}: no samples"
avg = sum(self._samples) / len(self._samples)
return f"{self._name}: avg={avg:.2f}ms over {len(self._samples)} samples"
Calling .summary() on a plain MetricCollector gives "requests: n=2"; calling the exact same method name on a LatencyCollector after recording 12.0 and 18.0 gives "p50_latency: avg=15.00ms over 2 samples" (verified: (12.0 + 18.0) / 2 = 15.00). Code that only knows it has a MetricCollector and calls .summary() gets the right behavior either way, that's the polymorphism.
Trade-offs & pitfalls
The pillars are not equally load-bearing in modern code: encapsulation and abstraction are used constantly and rarely controversial, while deep inheritance hierarchies are increasingly avoided in favor of composition ('composition over inheritance') once a hierarchy goes past one or two levels, because each additional layer makes behavior harder to predict from any single class definition. A senior answer should name that tension rather than presenting a 4-item inheritance-friendly hierarchy as the goal in itself.
Explain what happens mechanically when you write a try/except/finally block (or the equivalent in your language): what runs, in what order, when no exception occurs, when one is raised and caught, and when one is raised and NOT caught. Then walk through handling a file-I/O error inside a function that opens a file, using the construct to guarantee the file is always closed even when an error occurs.
Sample Answer
Direct answer
try marks a block whose exceptions you want to intercept; except runs only if a matching exception is raised inside the try; finally always runs, whether or not an exception occurred and whether or not it was caught, and it runs even if the exception propagates past this block entirely.
Structured elaboration
- No exception: the
tryblock runs to completion, everyexceptclause is skipped, thenfinallyruns. Nothing unusual happens. - Exception raised and caught: execution jumps out of the
tryblock the instant the exception is raised (any code after the raising line intrydoes NOT run), the first matchingexceptclause runs, thenfinallyruns. - Exception raised and NOT caught (no
exceptclause matches its type): the matching-exceptsearch fails,finallystill runs (this is the part people get wrong:finallyis not conditional on being caught), and only afterfinallycompletes does the exception continue propagating up to the caller. - The consequence that matters in practice:
finallyis the correct place for resource cleanup that must happen unconditionally, closing a file handle, releasing a lock, rolling back a partially-started operation, precisely because it is the one block guaranteed to run on every exit path from thetry.
Worked example
def no_exception():
order = []
try:
order.append('try')
except ValueError:
order.append('except')
finally:
order.append('finally')
return order
def caught_exception():
order = []
try:
order.append('try')
raise ValueError('boom')
except ValueError:
order.append('except')
finally:
order.append('finally')
return order
Running both (verified): no_exception() returns ['try', 'finally'] (the except clause never runs), caught_exception() returns ['try', 'except', 'finally']. A third case with a TypeError raised where only ValueError is caught confirms finally still runs before the TypeError propagates out to the caller, exactly as described above.
For the file-I/O case, opening a file and guaranteeing it closes even on a mid-read failure:
def read_lines(path):
f = open(path, 'r')
try:
return f.readlines()
finally:
f.close() # runs whether readlines() succeeds, raises, or the caller's except re-raises
This is exactly what a with open(path) as f: block (or Java's try-with-resources) does under the hood, they are sugar over a try/finally that closes the resource. In this pattern, whether to re-raise the error after logging it or return a sentinel value to the caller depends on whether the caller can meaningfully continue: propagate (let the exception continue, possibly after logging) when the caller cannot proceed without the data; return a sentinel only when the caller has a genuine, documented fallback.
Trade-offs & pitfalls
The most common mechanical mistake is assuming finally only runs when an exception was caught, when in fact it runs on every exit from try (normal completion, caught exception, uncaught exception, even a return inside the try block). The second most common mistake is putting cleanup code after the try/except instead of in finally, which silently skips cleanup on any path that doesn't hit that exact line, exactly the bug that finally exists to prevent.
Discuss the trade-offs between recursion and iteration: readability, call-stack usage, the risk of a stack overflow on deep input, and tail-call optimization availability across languages. Sketch a recursive factorial implementation and a tail-recursive or iterative variant, and explain why tail-call optimization is not guaranteed even when you write tail-recursive code (for example in Python).
Sample Answer
Direct answer
Recursion trades stack space and a per-call overhead for code that mirrors the problem's natural self-similar structure; iteration trades that clarity for constant stack usage and typically better raw performance. The concrete risk with recursion is a stack overflow on deep input, and the usual mitigating technique, tail-call optimization, is not guaranteed across mainstream languages (notably CPython does not do it).
Structured elaboration
- Readability: recursion often reads closer to the mathematical or structural definition of the problem (a tree, a fractal-like decomposition,
n! = n * (n-1)!). Iteration usually needs an explicit accumulator or work-list and can obscure that structure, especially for tree/graph problems. - Stack usage: each recursive call pushes a new stack frame (return address, local variables). A recursive call chain of depth
nusesO(n)stack space, while a well-written iterative loop usesO(1)auxiliary stack space (the loop variables live in one frame). - Stack overflow risk: if depth exceeds the runtime's limit, you get a hard failure (Python's
RecursionError, a native segfault-style crash in some languages). This is a real production risk whenever recursion depth is driven by input size rather than a small fixed bound. - Tail-call optimization (TCO): in a 'tail-recursive' function, the recursive call is the very last operation, nothing happens after it returns. A compiler or runtime that supports TCO can reuse the current stack frame for that call instead of pushing a new one, turning the recursion into a loop under the hood with
O(1)stack usage. Languages like Scheme and (in the target-relevant case) Java's Scala guarantee this for self-tail-calls; CPython deliberately does NOT implement it (a language design choice, not a limitation of the trick) partly because it would make stack traces less informative for debugging.
Worked example
def factorial_recursive(n):
if n <= 1:
return 1
return n * factorial_recursive(n - 1) # NOT tail-recursive: multiply happens after the call returns
def factorial_tail_style(n, acc=1):
if n <= 1:
return acc
return factorial_tail_style(n - 1, acc * n) # tail-recursive IN FORM, but Python still doesn't optimize it
def factorial_iterative(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
All three agree on small input (verified: factorial_recursive(10) == factorial_iterative(10) == factorial_tail_style(10) == 3628800). The difference shows up at depth: with CPython's default recursion limit of 1000, factorial_recursive(5000) raises RecursionError: maximum recursion depth exceeded (confirmed by running it), while factorial_iterative(5000) completes normally regardless of the tail-style rewrite, because CPython never collapses the recursive call chain into a loop. The same real-world shape shows up walking a deep hierarchical structure (a category tree, a nested comment thread): a recursive walker is elegant until the tree gets deep enough that the recursion limit, not the actual computation, is what fails.
Trade-offs & pitfalls
A correct senior answer does not claim 'just write tail-recursive code and it'll be fine' in a language like Python, that is a common and wrong mental shortcut. The real decision is: if depth is bounded and small (most tree structures in practice), recursion's readability usually wins; if depth scales with untrusted or unbounded input, convert to an explicit iterative version with your own stack (see the tree-traversal conversion question for a worked version of exactly that conversion) rather than relying on the language to save you.
You find a function that catches every exception and silently returns None on any error (a bare except that swallows the failure). What can go wrong with this pattern in production, and what should replace it? Describe the technical fix (which exceptions to actually catch, how to preserve the failure signal) before considering how you'd raise it with the author.
Sample Answer
Direct answer
A bare except: (or except Exception: with a silent return None) doesn't just handle the error you intended, it catches every error that happens to occur in that block and treats all of them identically, so a genuine bug (wrong type, a typo'd attribute, a logic error) gets misclassified as 'expected failure' and hidden from anyone who could act on it. The fix is to catch only the SPECIFIC exception you actually expect, and make failure visible (log it, re-raise it, or return a value the caller is forced to check) instead of silently returning a value indistinguishable from a normal result.
Structured elaboration
- Why this is dangerous, not just untidy:
Noneis frequently also a valid, meaningful return value elsewhere in the codebase. A caller receivingNonefrom this function cannot tell 'there was no data' from 'something crashed while getting the data', those are very different situations that need very different handling, and the swallowed exception has erased the distinction. - Why 'catch everything' is worse than it looks: a bare
exceptcatchesValueError(probably intended) but ALSOTypeError,AttributeError, evenKeyboardInterruptin some forms, errors that indicate a real bug in the calling code, not a data-quality issue the function was designed to tolerate. Narrowing to the specific expected exception type is what lets a genuine bug surface loudly instead of being absorbed by the same catch-all. - What replaces it: catch only the exception type(s) you actually expect and know how to handle; log enough context to diagnose it (what input caused it); then either re-raise (if the caller has no way to proceed without this data) or return an explicit, unambiguous sentinel that cannot be confused with a valid result (not bare
NoneifNoneis otherwise meaningful). - The review conversation: once the technical fix is clear, raising it with the author is a normal, low-friction code-review comment focused on the concrete failure mode ('this will hide a real TypeError as if it were expected'), not a judgment about the person, that's what keeps the fix landing quickly.
Worked example
def bad_parse(raw):
try:
return int(raw)
except Exception:
return None # catches ValueError AND TypeError identically
def good_parse(raw, logger):
try:
return int(raw)
except ValueError:
logger.warning("could not parse %r as int", raw)
raise # or: return a sentinel the caller is forced to check
Verified: bad_parse(None) returns None silently, giving no signal that int(None) actually raised a TypeError (passing None where a string/number was expected, a real bug at the call site, not a data-quality issue). good_parse(None, logger) instead lets that TypeError propagate uncaught (confirmed: it raises TypeError, not swallowed), because the function only catches ValueError. good_parse("not-a-number", logger) correctly logs a warning and re-raises ValueError (confirmed by execution), a case the function WAS designed to handle, with a visible trail.
Trade-offs & pitfalls
The judgment call is choosing between re-raising and returning a sentinel: re-raise when the caller genuinely cannot proceed without valid data (most cases); return an explicit sentinel only when the caller has a real, intentional fallback path for 'this record was unparseable' and the sentinel can't be confused with a legitimate value. What never belongs in either path is catching a broader exception type than you can actually reason about, that's the pattern that turns a narrow, expected failure mode into a general-purpose bug hiding place.
What is a closure, and what does it capture from its enclosing scope? Explain, with a small code example, how a closure or a callback holding a reference can keep an object alive longer than expected (for example through a reference cycle), and describe a practical strategy to avoid or detect that kind of memory retention in a long-running process.
Sample Answer
Direct answer
A closure is a function bundled together with references to the variables from its enclosing scope that it uses, captured by reference (not by value), so it keeps seeing the CURRENT value of those variables even after the enclosing function has returned. That captured reference can create a reference cycle, which is why a closure or callback can keep an object alive longer than you expect.
Structured elaboration
- What gets captured: a closure captures the variable itself (technically, the enclosing scope's cell), not a snapshot of its value at creation time. Two closures created from the same enclosing call share independent state; two closures created from the SAME variable in a loop share the same captured cell, which is the classic 'all my callbacks report the same, final loop value' bug.
- Why closures can leak memory: a closure keeps a live reference to everything it captures for as long as the closure itself is reachable. If you then store that closure back onto an object it captured (a callback registered on the very object it was built from), you've created object -> closure -> object, a reference cycle.
- Why reference counting alone can't free a cycle: CPython's primary memory management is reference counting, an object is freed the instant its reference count hits zero. In a cycle, each object holds a reference to the other, so neither one's count ever reaches zero on its own, even after nothing OUTSIDE the cycle references either of them. This is precisely why CPython also runs a separate cyclic garbage collector (
gcmodule) that periodically looks for groups of objects that reference each other but are unreachable from anywhere else, and frees them as a group. - Mitigation strategies: avoid storing a closure back onto the object it captures when you can restructure to avoid it; use
weakreffor a back-reference that shouldn't keep the target alive (a common pattern for observer/callback registries); or simply trust the cyclic collector for genuinely short-lived cycles and only investigate further if profiling shows real, growing retention in a long-running process.
Worked example
class Node:
def __init__(self, name):
self.name = name
self.on_event = None
def wire(node):
def handler(): # closure: captures `node`
return f"{node.name} handled"
node.on_event = handler # node -> handler -> node : a cycle
return handler
Verified by running it with gc.disable() and a weakref to the node: after del n (dropping the only external reference), the node is STILL alive (ref() is not None is True) because the cycle keeps both objects' reference counts above zero. Re-enabling the collector and calling gc.collect() reclaims it (ref() is None becomes True immediately after), confirming the cyclic collector, not reference counting, is what actually frees this pattern.
Trade-offs & pitfalls
In a long-running service, this usually shows up as slow, steady memory growth rather than an obvious crash, because the cyclic collector DOES eventually run and free most cycles; the real danger is cycles involving objects with a __del__ method (historically these were UNCOLLECTABLE by the cyclic GC before Python 3.4, and even post-3.4 they add real collection overhead) or large cycles that make each collection pass more expensive as the live object graph grows. The fix is rarely 'stop using closures', it's to be deliberate about back-references specifically, using weakref where a callback registry would otherwise hold the only thing keeping a large object graph alive.
Unlock Full Question Bank
Get access to all 12 Programming Fundamentals interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.