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.
Two pieces of code (for example, two API endpoint handlers) share very similar data-mapping and error-handling logic. Show how you would extract the shared behavior into a small, well-named abstraction while preserving each caller's distinct needs and clarity.
Sample Answer
Direct answer. Extract the common shape (try/fetch, 404 handling, error handling) into one small higher-order function, and let each caller supply only the piece that actually differs: how to map the fetched row into a response body.
Before
async function getUser(req, res, db) {
try {
const row = await db.find('users', req.params.id);
if (!row) return res.status(404).json({ error: 'not found' });
res.status(200).json({ id: row.id, name: row.full_name, email: row.email_address });
} catch (e) {
res.status(500).json({ error: 'internal error', detail: e.message });
}
}
// getOrder duplicates the same try/404/500 shape with a different mapping
After
function makeGetByIdHandler(db, table, mapRow) {
return async function handler(req, res) {
try {
const row = await db.find(table, req.params.id);
if (!row) return res.status(404).json({ error: 'not found' });
res.status(200).json(mapRow(row));
} catch (e) {
res.status(500).json({ error: 'internal error', detail: e.message });
}
};
}
const getUser = (db) => makeGetByIdHandler(db, 'users',
(row) => ({ id: row.id, name: row.full_name, email: row.email_address }));
const getOrder = (db) => makeGetByIdHandler(db, 'orders',
(row) => ({ id: row.id, total: row.total_amount, status: row.order_status }));
Verified against a fake db/response harness: both the success path (200 with mapped body) and the not-found path (404) produce byte-identical responses before and after the refactor.
Why an abstraction, not just a copy-paste tweak
The part that varies (table name, row-to-response mapping) is passed IN as data/functions; the part that's identical (control flow: try, 404 check, catch, 500) lives in exactly one place. If the error-handling shape needs to change later (say, adding a request ID to the 500 response), it changes once, and every endpoint built on makeGetByIdHandler gets the fix automatically instead of needing the same edit copy-pasted into every handler.
Preserving clarity per caller
Each concrete handler (getUser, getOrder) still reads as a short, self-contained declaration of WHAT it maps, not HOW the request/response machinery works -- the abstraction doesn't hide the caller's own logic, only the boilerplate every caller would otherwise repeat.
Trade-offs and pitfalls
- This is a good abstraction only because the two callers' DIFFERENCES (the mapping function) are cheap to express as a parameter; if the endpoints started needing genuinely different control flow (one needs a second DB lookup, one needs caching), forcing them through the same higher-order function would make the abstraction leak and become harder to read than the duplication it replaced.
- Watch for the abstraction picking up special-case parameters over time ('handle table X differently') -- that's the sign the shared function is trying to do two things and should split back into two.
- Extracting too early, on the FIRST occurrence of similar code (rather than the second or third), risks guessing wrong about which parts are truly invariant.
Explain the Single Responsibility Principle. What does 'responsibility' mean precisely (a reason to change, not merely 'does one thing'), and how do you recognize an SRP violation in a class or module you're reading for the first time?
Sample Answer
Direct answer. Single Responsibility Principle: a class or function should have exactly one reason to change. 'Responsibility' means an axis of change owned by a specific actor or concern, not literally 'does one thing' in a narrow procedural sense.
What 'a reason to change' actually means
A class that both formats a report AND persists it to disk has two reasons to change: the business wants a different report layout, or the ops team wants a different storage backend. Those changes come from different stakeholders on different timelines. When they're tangled in one class, a storage change risks breaking formatting and vice versa, and two people can't safely work on the two concerns in parallel.
Recognizing a violation on first read
- The class name is vague or conjunctive:
UserManager,OrderProcessor,ReportHelperAndSaver-- names with 'and' or generic suffixes likeManager/Handler/Utilare a strong tell. - Methods on the class naturally group into unrelated clusters that never call each other (e.g., half the methods touch a database, half touch an HTTP client, and neither group references the other).
- You can't describe the class in one sentence without using 'and'.
- Changing behavior for one caller's needs forces you to touch code that a completely different caller depends on.
Worked example
A UserService that validates input, applies business rules, persists to the database, AND sends a welcome email has (at least) four responsibilities. Splitting it into a UserValidator, UserRules, a repository, and a WelcomeEmailSender means: a change to email copy touches only WelcomeEmailSender; a change to the persistence layer (say, swapping ORMs) touches only the repository; and each piece can be unit-tested in isolation without mocking the other three.
Trade-offs and pitfalls
- SRP is not 'one method per class' -- that's over-splitting and creates its own maintenance cost (you now have to trace behavior across ten tiny classes instead of one). The right granularity is 'one reason to change,' not 'one line of code.'
- Don't force a split just to satisfy a rule when the two concerns are ALWAYS going to change together in practice; if they share a single reason to change, keeping them together is the correct call, not a violation.
- SRP applies at multiple altitudes: a single function, a class, and a service/module. The 'reason to change' framing works at all three, but the actors change (a function's actor might be 'the caller's contract'; a service's actor might be 'a whole team').
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.
What is a code smell? Name five smells you encounter most often in a codebase that has been under deadline pressure for a while, and for each give a one-sentence remediation approach.
Sample Answer
Direct answer. A code smell is a surface signal, not a bug in itself, that usually points to a deeper structural problem: the code works today but will resist the next change. It's a heuristic for WHERE to look, not proof that something is wrong.
Five smells common under deadline pressure
- Long method -- a function that keeps growing because it's easier to add one more
ifthan to stop and restructure. Remediation: extract by responsibility (see S5) as soon as a function needs a comment to separate its 'sections.' - Duplicated code -- the same logic copy-pasted with small tweaks because extracting a shared abstraction felt slower under a deadline. Remediation: extract the shared part once there are two clear copies (the classic 'rule of three' guards against over-extracting on the first duplicate).
- God object/class -- one class or module that ends up owning unrelated responsibilities because it was the easiest place to bolt on 'just one more thing.' Remediation: split along 'reason to change' (SRP), migrating callers incrementally rather than in one big rewrite.
- Shotgun surgery -- a single conceptual change (e.g., adding a new payment method) requires touching a dozen files because the concept isn't encapsulated anywhere. Remediation: consolidate the scattered logic behind one seam (a class, interface, or module) so future changes touch one place.
- Primitive obsession -- passing raw strings/ints around for things that are really domain concepts (an email, a currency amount, a user ID), losing the validation and meaning a real type would carry. Remediation: introduce small value types/wrappers so invalid states become unrepresentable rather than merely 'usually correct.'
Why deadline pressure specifically produces these
Under pressure, the fastest LOCAL change is almost always to keep extending what's already there (one more branch, one more copy-paste, one more method on the class you already have open) rather than to pause and restructure. Each individual shortcut is locally rational; the smell accumulates because nobody's shortcut budget includes 'time to undo the last five shortcuts.'
Trade-offs and pitfalls
- Smells are a starting point for investigation, not an automatic verdict -- a long method that's a single linear sequence of well-named steps with no branching can be more readable than five tiny indirections that force you to jump around a file.
- Don't chase every smell with equal urgency; prioritize by where the churn and bug density actually are (see the complexity-metrics survivor for how to find that objectively) rather than refactoring whatever offends you first.
- Naming a smell is only useful if it's followed by a concrete remediation plan; 'this is a god object' without a proposed split is just a complaint.
You need to add unit tests to legacy code that talks directly to a third-party client (a database, a cloud API) with no seam for a test double. Explain how you'd introduce a seam so you can test the logic without hitting the real dependency.
Sample Answer
Direct answer. Introduce a seam -- a thin interface or wrapper between your logic and the hard-to-test dependency -- so tests can substitute a fake implementation without touching the real database/API, then test your logic against that seam instead of the real thing.
The problem
def sync_user(user_id):
conn = ThirdPartyDB.connect() # real network call, no seam to intercept
row = conn.query(f"SELECT * FROM users WHERE id={user_id}")
return transform(row)
There's no place to inject a test double: the function reaches OUT and grabs its own dependency internally, so any test either needs a real (or realistically faked) ThirdPartyDB running, or it can't test transform's logic in isolation at all.
Introducing a seam
class UserRepository:
def __init__(self, db_client):
self.db_client = db_client # injected, not grabbed internally
def fetch_user_row(self, user_id):
return self.db_client.query(f"SELECT * FROM users WHERE id={user_id}")
def sync_user(user_id, repo: UserRepository):
row = repo.fetch_user_row(user_id)
return transform(row)
A test now passes a UserRepository wrapping a FAKE db_client (an in-memory stub returning a canned row) -- sync_user's actual logic (transform) is tested without any real network dependency, and the seam (UserRepository) can separately get a thin integration test against the real client if desired.
Choosing where the seam goes
Put the seam at the boundary between YOUR logic and the THIRD-PARTY specifics -- not deeper. Here, UserRepository isolates 'how we talk to this specific database'; everything on the sync_user side of that seam is pure application logic, testable with a simple fake that doesn't need to reimplement the third party's actual query semantics.
Trade-offs and pitfalls
- A seam that's too thin (barely wrapping the third-party call) doesn't buy you much; a seam that's too thick (re-implementing significant third-party logic in your fake) risks the fake diverging from real behavior and giving false test confidence -- calibrate the fake to return realistic shapes for the cases your logic actually branches on.
- Introducing a seam is itself a small refactor of legacy code with no tests yet -- do it carefully (ideally under a characterization test on the OUTER function first) so the seam-introduction step itself doesn't silently change behavior.
- Keep at least one lightweight integration test that exercises the REAL third-party client occasionally (even if slow/flaky and run less often), since fakes can drift from reality if the third party's behavior changes and nothing ever re-validates the assumption.
Unlock Full Question Bank
Get access to all 37 Clean Code, Refactoring, and Maintainability interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.