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.
Design a program (not just a tool rollout) to raise coding standards across an organization: what training, mentoring, and measurable milestones would you include, and how do you get buy-in from engineers who see this as overhead?
Sample Answer
Direct answer. Treat this as a change-management program, not a tooling rollout: pair mandatory automation (which removes debate entirely) with voluntary, incentivized skill-building (training, mentoring, visible wins) so the standards feel like a shared craft investment rather than a compliance mandate imposed from outside.
Program design
- Content: start from a small, high-leverage set of standards (naming, function size, the specific smells causing the MOST real pain in this codebase's incident history) rather than a comprehensive style guide nobody will read -- credibility comes from solving real, felt pain first.
- Automation for anything mechanical: formatting and simple lint rules are enforced via tooling from day one, removing them entirely from human debate or 'training' -- nobody needs a workshop on tab-vs-space.
- Training for judgment-based standards: run short, practical workshops (not lectures) using REAL examples from the team's own codebase/incident history, since judgment-based standards (when to extract an abstraction, how to name well) don't automate and need practiced instinct, not just awareness.
- Mentoring/pairing: pair newer or more skeptical engineers with engineers who already practice these standards well, on REAL work, so the standard is demonstrated in context rather than asserted in a slide deck.
- Measurable goals: track leading indicators (percentage of PRs passing automated checks without manual intervention, review comment volume on style/naming trending down) and lagging indicators (incident rate, time-to-onboard a new engineer) -- both matter, since leading indicators show adoption and lagging indicators show it's actually working.
- KPIs with guardrails against gaming: pair any metric with periodic qualitative sampling (an experienced engineer reviews a sample of recent PRs) so metrics can't be satisfied by superficial compliance (renaming one variable to 'pass' a linter check while leaving the underlying design smell untouched).
Building buy-in, not just compliance
- Involve skeptical senior engineers in DEFINING the standards, not just receiving them -- standards that feel imposed by a committee they weren't part of get quiet resistance; standards they helped shape get real ownership.
- Celebrate and publicize concrete wins (an incident that WOULD have happened but didn't, because a new test caught it) so the program has visible, credible evidence of value beyond an abstract mandate.
Trade-offs and pitfalls
- A program that's ALL mandate (enforcement) with no visible value story tends to produce compliance without real behavior change -- people satisfy the letter of the rule while resenting it, which shows up later as pushback the moment enforcement weakens.
- Don't let the KPI dashboard become the goal itself (Goodhart's Law) -- pair quantitative tracking with periodic human judgment sampling so the program stays honest about whether it's actually improving outcomes, not just moving a number.
Discuss the trade-offs between using exceptions and explicit error codes or return values for error handling in backend services. Cover language-specific idioms in Java, Python, Go, and Node.js, how to propagate errors cleanly across layers, and how to design an API so that error cases are explicit and testable.
Sample Answer
Direct answer
Exceptions make error handling implicit and easy to accidentally skip, but keep the success-path code uncluttered; explicit error codes or return values force every caller to consciously handle the failure case, at the cost of more verbose code at every call site. Which is idiomatic depends heavily on the language: Go and Rust favor explicit returns, Java and Python favor exceptions, and Node.js uses a mix depending on whether the code is synchronous or promise-based.
Structured elaboration
Exceptions (Java, Python). An exception unwinds the call stack automatically to the nearest handler, which keeps the success path readable (no error-checking boilerplate after every call) but makes it easy for a caller to simply forget to catch something, especially in a language like Java where checked exceptions are used inconsistently, or Python where nothing in a function's signature indicates what it might raise at all. The propagation is implicit: an uncaught exception silently travels up through every intermediate frame until something catches it or the program crashes, which can hide exactly where a failure needs handling until it's discovered in production.
Explicit error codes and return values (Go, Rust). Go's (result, error) return convention and Rust's Result<T, E> type both force the caller to explicitly acknowledge the possibility of failure at every single call site, since the value cannot be used without either handling or explicitly ignoring the error component. This makes control flow highly visible (every fallible call is visually marked in the code) at the cost of real verbosity: a chain of five fallible operations in Go often means five if err != nil { return err } blocks in a row.
Node.js: a genuine mix. Synchronous code commonly throws; asynchronous code built on Promises resolves or rejects, and an unhandled promise rejection is its own distinct failure mode from an uncaught synchronous exception, one that historically could fail silently unless the runtime was configured to treat it as fatal. A codebase mixing callback-style, Promise-style, and async/await code can end up with three different error-propagation conventions active at once, which is itself a common source of bugs.
Designing an API to make error cases explicit and testable. Regardless of the language's own convention, a well-designed API surface names its possible failure modes in its own contract, not just in its implementation: a function's documentation (or its type signature, for languages that support a Result-like return type even where the language itself favors exceptions) should say what can go wrong, so a caller does not have to read the implementation to find out. This can be tested directly: for each documented failure mode, a unit test should assert the specific error type or code produced, not just that "an error occurs".
Worked example
The same operation, fetch-a-user-then-update-their-balance, in Go versus Python: in Go, user, err := getUser(id); if err != nil { return err }; err = updateBalance(user, amount); if err != nil { return err } makes both fallible steps visually explicit, and it is a compile error to use user before checking err. In Python, user = get_user(id); update_balance(user, amount) reads more cleanly, but nothing in the code signals that either call can raise, and a caller three call-frames up who forgot to wrap this in a try/except will simply see an unhandled UserNotFoundError propagate as an unhandled exception, potentially crashing an entire request handler for a case that a Go-equivalent caller would have been forced to at least acknowledge.
Trade-offs and pitfalls
The most common mistake when working against the grain of a language's own idiom is inconsistency: mixing exceptions and error-code returns within the same Python or Java codebase (some functions raise, some return None or a special error object on failure) forces every caller to remember, function by function, which convention applies, which is worse than either convention applied consistently. A second common mistake specific to Go is checking err != nil and then continuing to use a possibly-invalid result anyway due to a copy-paste error, since Go's convention does not prevent that the way a language with a true sum type like Rust's Result does.
You want to introduce mandatory linting and a consistent style guide across a codebase (or many repos) that has never had one, without drowning teams in noisy diffs or blocking urgent work. Describe your rollout plan: scope, sequencing, and how you handle legacy code that fails the new rules on day one.
Sample Answer
Direct answer. Roll out in WARN-then-ENFORCE stages, scoped to new/changed code first rather than the whole legacy codebase at once, so teams get advance visibility without a flood of unrelated diffs blocking urgent work on day one.
A staged rollout plan
- Warn-only phase: enable the linter/formatter in CI as a non-blocking report for a few weeks, so teams see what WOULD fail without anything actually blocking merges yet -- this surfaces the scale of existing violations before anyone is forced to fix them under pressure.
- Scope enforcement to the DIFF, not the whole file: a common and effective rule is 'new/changed lines must pass; pre-existing violations in untouched lines are grandfathered' -- this stops the bleeding immediately without requiring a giant one-time cleanup of the entire legacy codebase.
- Auto-fix what can be auto-fixed: run the formatter across the whole repo ONCE, in a single, isolated, reviewed PR (ideally with
git blame --ignore-revsupport configured so this mass-reformat doesn't pollute blame history for actual logic changes), separating pure formatting noise from real code changes forever after. - Enforce blocking status on new code once the warn-only phase has run its course and teams have had time to adjust their workflows (editor integration, pre-commit hooks).
- Track and periodically pay down legacy violations as a separate, lower-priority backlog, ideally opportunistically (fix violations in a file when you're already touching it for another reason) rather than a dedicated sweep that competes with feature work.
Avoiding the two failure modes
- Breaking builds for many teams: the diff-scoped enforcement plus a WARN period before ENFORCE avoids a big-bang day where hundreds of pre-existing violations suddenly block everyone's unrelated PRs.
- Silent non-adoption: making it non-blocking forever (never moving past WARN) means violations just accumulate with a report nobody reads -- commit to a concrete date when warn becomes enforce, communicated in advance.
Trade-offs and pitfalls
- The single, whole-repo auto-format commit is disruptive to any in-flight branches at that moment (merge conflicts on every file touched) -- schedule it for a quiet period and communicate it clearly, and configure blame-ignore-revs immediately so it doesn't permanently obscure history.
- 'New/changed lines only' enforcement can be gamed by refactoring a file just enough to dodge triggering full-file linting, or conversely can feel unfair when a small logic change in an old, unlinted file suddenly triggers a wall of unrelated formatting fixes -- a common refinement is enforcing only on lines actually touched by the diff, not the whole file the diff happens to be in.
Plan an incremental migration from Objective-C to Swift in a large, actively-shipping production iOS app. How do you handle interoperability during the transition, and how do you decide what to port first?
Sample Answer
Direct answer. Bridge, don't cut over all at once: keep Objective-C and Swift interoperating via bridging headers throughout the transition, port leaf/low-dependency modules first, and let the ratio shift gradually while the app keeps shipping releases the whole time.
Managing interoperability
- Objective-C and Swift can call each other directly within the same target via a bridging header (Obj-C calling Swift) and Swift's automatic Objective-C interop (Swift calling Obj-C) -- this means you don't need a hard cutover; both languages coexist naturally in the same codebase for as long as needed.
- Watch for interop friction points: Swift's stricter optionals/nullability annotations need to be added to Objective-C headers (
nullable/nonnull) for clean bridging; Objective-C generics and lightweight generics translate imperfectly and sometimes need explicit annotations to bridge cleanly.
What to port first
- New code: write all NEW features in Swift from day one -- this stops growing the Objective-C surface immediately, even before any porting of existing code begins.
- Leaf modules with few dependents: utility classes, model objects, and self-contained components with a small, stable interface are the safest first ports -- low blast radius if something's subtly different, and they prove out the interop patterns before tackling anything load-bearing.
- Avoid porting deeply-coupled, actively-changing code early: a view controller under active feature development is a bad first target -- you'd be fighting both the port AND ongoing feature changes simultaneously, maximizing risk for the riskiest code.
- Defer performance-critical or deeply Objective-C-runtime-dependent code (heavy use of
NSInvocation, dynamic method swizzling, KVO-heavy patterns) until later, since these interact with Objective-C's dynamic runtime in ways that need careful individual verification when ported.
Build system and release cadence considerations
- Modern Xcode handles mixed-language targets natively, but CI build times can grow during the transition (compiling both languages); budget for that rather than being surprised by it.
- Keep shipping REGULAR releases throughout -- a multi-month 'no releases while we port' approach compounds risk (a longer integration gap before real user feedback) instead of reducing it; the whole point of doing this incrementally is that each release is a small, verifiable step.
Trade-offs and pitfalls
- Bridging header maintenance itself has an ongoing cost (every Swift type exposed to Objective-C needs
@objcannotations and careful handling of Swift-only features like enums with associated values, which don't bridge cleanly) -- budget for this friction rather than assuming interop is free. - Don't port code just because it's 'old' -- prioritize by where Objective-C's dynamic features are actively causing pain (crashes, hard-to-debug issues) or where new feature work is about to touch that code anyway, opportunistically, rather than a blanket top-to-bottom sweep.
Plan a migration of a large Android app from an MVC-ish pattern (Activities/Fragments holding logic) to MVVM using Jetpack components. How do you keep the app releasable at every step of the migration?
Sample Answer
Direct answer. Extract business logic out of Activities/Fragments into ViewModels incrementally, keeping the app releasable at every step by having the ViewModel and the old Activity-held logic coexist temporarily, with the UI layer delegating to whichever is currently authoritative for each specific piece of state.
A releasable-at-every-step plan
- Introduce a ViewModel alongside the existing Activity/Fragment logic for ONE screen at a time, without removing anything from the Activity yet -- both can coexist since a ViewModel is just an additional, lifecycle-aware holder of state.
- Migrate one piece of state/logic at a time from the Activity into the ViewModel, having the Activity read from the ViewModel (via LiveData/StateFlow observation) instead of holding the state directly -- verify UI behavior is unchanged after each individual piece moves, not just at the end of the whole screen's conversion.
- Move business logic (network calls, data transformation) into the ViewModel before moving UI-adjacent logic (view state, click handling) -- business logic is usually easier to unit-test in isolation and provides the biggest early payoff (testability without an Android runtime).
- Convert Activities to be thin observers of ViewModel state last, once the ViewModel actually holds the real logic -- at this point the Activity's job shrinks to binding UI to ViewModel state and forwarding user actions, which is the MVVM end state.
- Ship after each screen's migration, not after the whole app is converted -- since each screen's ViewModel is self-contained, converting screen A doesn't require screen B to also be converted before releasing.
Handling shared/cross-screen state during the transition
If multiple screens share state currently held in an Activity or a singleton, that shared state needs its OWN migration plan (often into a shared ViewModel scoped to a navigation graph, or a repository layer) BEFORE the individual screens can cleanly extract their own logic -- migrating a screen whose state is entangled with others first is much harder than migrating an isolated screen, so sequence isolated screens first.
Keeping the app releasable
- Each screen's migration is independently testable and shippable; a partially-migrated app (some screens on MVVM, some still Activity-heavy) is a normal, safe intermediate state, not a broken one, as long as neither approach depends on the other being fully converted.
- Regression-test each migrated screen's user-visible behavior (via UI/instrumentation tests) before and after its conversion, the same discipline as any other legacy refactor.
Trade-offs and pitfalls
- Rushing a whole screen's conversion in one large PR (rather than one piece of state at a time) makes it much harder to isolate WHICH change introduced a behavioral regression if the migrated screen doesn't behave identically.
- Watch for Activity/Fragment lifecycle edge cases (configuration changes, process death) that a ViewModel is specifically designed to survive but the old Activity-held state was not -- confirm the migrated behavior is at least as correct as before, not just superficially similar in the happy path.
Unlock Full Question Bank
Get access to all 19 Clean Code, Refactoring, and Maintainability interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.