Design Patterns Middle cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. Which pattern was applied in this refactoring?
// before function price(type, sum) { if (type === "vip") return sum * 0.8; if (type === "sale") return sum * 0.9; return sum; } // after const discounts = { vip: s => s * 0.8, sale: s => s * 0.9, regular: s => s }; const price = (type, sum) => discounts[type](sum);Correct answer: Strategy: the algorithms were moved into interchangeable functions
Each discount is a separate strategy, and a new one is added without editing the
pricefunction (also an example of OCP). In JS, a strategy is often just an object of functions instead of a class hierarchy.2. Why does
subscribein an Observer implementation usually return an unsubscribe function?function subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); }Correct answer: So the subscriber can easily unsubscribe and avoid a memory leak
The returned function fits neatly into
useEffectcleanup:useEffect(() => store.subscribe(fn), []). Without unsubscribing, the subject keeps references to callbacks of unmounted components - a leak and extra calls. Redux, Zustand anduseSyncExternalStorework this way.3. How does Decorator differ from Proxy if their structure is similar?
Correct answer: By intent: Decorator adds behavior, Proxy controls access to the object
Both wrap an object with the same interface. Decorators are usually stacked to build up functionality (logging + cache + retry). A proxy manages lifecycle and access: lazy loading, permission checks, a remote object. Many patterns differ precisely by their goal.
4. How does Adapter differ from Facade?
Correct answer: Adapter fits an interface to the expected one, Facade simplifies working with a subsystem
An adapter usually wraps one object and makes it compatible with existing code. A facade defines a new, simpler interface over many objects. In practice, an API layer often combines both: a facade over HTTP and adapters for the data.
5. When is an Abstract Factory appropriate instead of a simple factory?
Correct answer: When you need families of related, compatible objects
Example: a UI kit for two platforms - the factory creates a button, an input and a modal in one style, and they can't be mixed. A simple factory picks one product by a parameter. Don't introduce an abstract factory if there's only one family.
6. What's dangerous about a module-level singleton (
export const cache = new Map()) in an SSR app?Correct answer: On the server the module is shared by all requests, so users' data gets mixed
In the browser, a module variable lives within one tab. A server process serves thousands of users, and a shared module-level cache or store can serve one user's data to another. Request state is created per request (e.g. React's
cache(), aQueryClientper request).7. How do you implement undo/redo with the Command pattern?
Correct answer: Keep stacks of commands, each with
executeandundoAn executed command goes onto the
undostack; undoing callsundo()and moves the command to theredostack. A new action clearsredo. An alternative for immutable state is the Memento pattern: keep previous versions of the state.8. Why are
isLoading,isError,isSuccessflags worse than an explicit state?type State = | { status: "idle" } | { status: "loading" } | { status: "success"; data: User } | { status: "error"; error: string };Correct answer: Flags allow impossible combinations
Three boolean flags give 8 combinations, including meaningless ones like "loading and error at once". A discriminated union is essentially the State pattern / a finite state machine: transitions are explicit, and
datais available only insuccess.9. What's the risk of a global event bus as an implementation of Mediator?
Correct answer: Data flows become implicit and hard to trace
Decoupling via event names is convenient, but as the app grows, connections hide in strings, cycles appear, and "ghost" subscribers emerge. That's why React apps usually prefer explicit flows: props, Context, a store with selectors.
10. Which pattern do axios interceptors or
fetchwrappers implement?Correct answer: Chain of Responsibility: the request passes through handlers
Interceptors add a token, log, refresh the session on 401, transform errors - each is responsible for its own step and passes the request on. Order matters and should be fixed explicitly.
11. How do you render a comment tree of arbitrary depth?
function Comment({ comment }) { return ( <li> {comment.text} {comment.replies.length > 0 && ( <ul>{comment.replies.map(r => <Comment key={r.id} comment={r} />)}</ul> )} </li> ); }Correct answer: With a recursive component - the Composite pattern for UI
Nodes and leaves are handled the same way, so the component calls itself for its children. For very deep or large trees, add virtualization or "Show more", and store the data normalized.
12. How does a generator help implement an Iterator for a paginated API?
Correct answer: It yields items one by one and requests the next page lazily
An async generator hides cursors and page numbers: the consumer writes
for await (const item of allItems())and can stop at any time without loading anything extra. Traversal logic is separated from processing logic.13. How does Template Method differ from Strategy?
Correct answer: Template Method varies steps via inheritance, Strategy via composition
Template Method fixes the algorithm's skeleton in a base class, and the variation is set by a subclass (statically). A strategy is passed to an object and can change at runtime. In JS, composition is usually preferred: pass step functions.
14. Why does immutable state simplify the Memento pattern?
Correct answer: Old versions don't change, so a reference is enough
With mutations, a memento requires a deep copy. With immutable updates (spread, Immer), unchanged parts are reused (structural sharing), and change history costs almost nothing. That's how time travel in Redux DevTools works.
15. Which pattern does a Babel or ESLint plugin use when it walks the AST with
Identifier()andCallExpression()methods?Correct answer: Visitor: operations on tree nodes are moved into a separate object
Visitor lets you add new operations over a structure (checks, transformations) without changing the node classes. The traverser calls the visitor's method for each node type.
16. Notifications come in three types and are sent over three channels (email, push, SMS). Which pattern saves you from 9 classes?
Correct answer: Bridge: the notification type and delivery channel evolve independently
Bridge separates the abstraction (notification type) from the implementation (channel) and links them via composition: 3 + 3 classes instead of 3 × 3. A new channel is added without changing the types.
17. Why have a layer of "repositories" or API services on the frontend instead of calling
fetchdirectly in components?Correct answer: Components don't know about transport and API format, which is easy to replace and mock
A repository hides where data comes from (REST, GraphQL, cache, mocks) and returns domain objects. When an endpoint changes, one place is edited, and tests replace the whole repository. TanStack Query hooks often call exactly such functions.
18. How do you inject a dependency into React components so you can swap the API client in tests?
Correct answer: Pass the client via a Context provider and wrap with a different value in tests
Context is React's built-in DI mechanism:
<ApiProvider client={mockClient}>in tests and Storybook, the real client in the app.QueryClientProviderand the Redux store provider work the same way.19. Which of these situations violates the Liskov Substitution Principle?
Correct answer: A subclass overrides a method and throws "Not implemented"
Code working with the base type doesn't expect an exception - substitution breaks the program. It's usually a sign that the hierarchy is wrong and the interface should be split (ISP). LSP doesn't forbid adding new methods.
20. A
UserCardcomponent takesuser: User(30 fields) but uses only the name and avatar. Which principle is violated?Correct answer: Interface Segregation: the component depends on data it doesn't need
With a narrow interface
{ name, avatarUrl }, the component can be used for a comment author or a chat participant, and tests don't need a full object. Also, changes to theUsertype won't affect the component.21. What does the Law of Demeter say about
order.customer.address.city.name?Correct answer: The code knows about objects that are too far away - talk to your neighbors
"Talk only to your friends": long chains tie code to the internals of many objects, and a change in any of them breaks the caller. The fix is a method or selector like
getDeliveryCity(order).22. What is unidirectional data flow in the Flux architecture?
Correct answer: Action → dispatcher → store → view, in a loop
Flux appeared at Facebook as a response to tangled two-way connections in MVC. The view doesn't change the store directly; it dispatches an action. Redux simplified the idea: one store and pure reducers instead of a dispatcher and several stores.
23. How does MVVM differ from React's approach?
Correct answer: MVVM uses two-way binding, React uses one-way data flow
Angular and Vue support two-way binding (
v-model,[(ngModel)]): field changes automatically go into the model. In React, the value and handler are wired explicitly (value+onChange) - more code, but a more transparent data flow.24. Which patterns can you see in Redux?
Correct answer: Command (actions), Observer (subscribe), a fold (the reducer)
An action is an object describing an intent (like a Command), the store notifies subscribers (Observer), the reducer folds a stream of actions into state, and middleware forms a chain of responsibility. This helps explain where Redux's strengths and limitations come from.
25. What is the order of Feature-Sliced Design layers from top to bottom?
Correct answer: app → pages → widgets → features → entities → shared
In FSD, a module can import only from layers below it:
featuresuseentitiesandshared, but notwidgets. This prevents circular dependencies and makes the impact of changes predictable.26. Why does every slice in FSD have a public API (
index.ts)?Correct answer: So outside code depends only on the slice's explicit exports
A public API is the module's contract (a Facade): the internal structure can change as long as the exports don't. A linter (Steiger, eslint plugins) forbids "deep" imports that bypass
index.27. How can barrel files (
index.tsre-exporting everything) do harm?Correct answer: They can slow down builds and tests and cause circular imports
Importing one function from a large barrel can force the bundler and test runner to parse the whole module graph, and mutual re-exports easily form cycles. Fixes: narrow public APIs, direct imports within a module,
optimizePackageImportsin Next.js.28. What's the main rule of Clean Architecture?
Correct answer: Dependencies point inward: business rules don't know about UI, DB or frameworks
Entities and use cases are at the center, while frameworks, DB and UI are in the outer circles and depend on the inner ones. Then business logic can be tested without a browser, and the framework changed without rewriting the rules. For the frontend, the approach is often simplified.
29. Where should business rules (e.g. discount calculation) live in a frontend app?
Correct answer: In pure functions of a domain layer used by components and hooks
Rules scattered across components get duplicated and are hard to test. Pure functions in
entities/domainare reused across screens, on the server and in tests without rendering.30. What does Atomic Design describe?
Correct answer: A UI hierarchy: atoms → molecules → organisms → templates → pages
Brad Frost's methodology for design systems: a button and an input are atoms, a search field with a button is a molecule, a header is an organism. Atoms in Jotai are a different concept (units of state).
31. What is shotgun surgery?
Correct answer: One change requires edits in many places
For example, adding a new order status requires edits in 12 files. It's a sign that one piece of knowledge is smeared across the code (a violation of DRY and cohesion). The cure is gathering the related logic into one module.
32. What is feature envy?
Correct answer: A function works more with another object's data than with its own
If an
OrderViewmethod keeps reaching intocustomer's fields and computing things from them, the logic should move closer to the data - into the customer module. This increases cohesion and simplifies changes.33. What is primitive obsession, and how is it treated?
Correct answer: Domain concepts as bare strings; use value types
userId: string,price: numberare easy to confuse with other strings and numbers. Value objects (Money), branded TS types (UserId) and enum-like unions make such mistakes impossible and gather validation in one place.34. Why do people say "duplication is cheaper than the wrong abstraction"?
Correct answer: Premature generalization accumulates flags and couples unrelated cases
A shared component for two similar screens gradually gets
isAdmin,variant,hideFooter… and becomes worse than copies. The AHA principle (Avoid Hasty Abstractions) and the "rule of three": generalize when the repetition has become obvious.35. What is the Null Object pattern?
const noopLogger = { info() {}, error() {} }; function createService(logger = noopLogger) { /* ... */ }Correct answer: A stub with the same interface instead of
nullchecksInstead of
if (logger) logger.info(...)all over the code, a safe stub is passed in. This simplifies the code and eliminates "cannot read property of null" errors.36. How do you implement lazy initialization of a heavy object?
let client; export function getClient() { return (client ??= createHeavyClient()); }Correct answer: Create the object on first access and reuse it afterwards
Lazy initialization saves startup time and resources if the object may not be needed. It's often combined with dynamic
import()for heavy SDKs. Remember SSR: on the server such a module-level cache is shared by all requests.37. What's wrong with mixins (
Object.assign(Class.prototype, mixin))?Correct answer: Implicit dependencies, name clashes, unclear origin of methods
Methods "appear" in the class from who knows where, and mixins can overwrite each other and rely on each other's fields. React dropped mixins back in the class component era; today hooks and composition solve the same problem.
38. What is the Registry pattern, using plugins as an example?
const renderers = new Map(); export const register = (type, fn) => renderers.set(type, fn); export const render = (block) => renderers.get(block.type)?.(block);Correct answer: Handlers register by key, and the core doesn't know about them
This is how extensible systems are built: CMS editor blocks, dashboard widgets, validation rules. A new type is added by registration, without changing the core (OCP).
39. How does a mock differ from a stub in tests?
Correct answer: A stub returns canned data, a mock also verifies calls
Test doubles: dummy (a placeholder), stub (canned answers), spy (records calls), mock (with expectations about calls), fake (a simplified working implementation, e.g. an in-memory repository). Dependency injection makes substitution easy.
40. What is the "test pyramid"?
Correct answer: Many fast unit tests, fewer integration tests and very few e2e tests
Lower levels are cheap and fast; upper ones are closer to reality but slow and brittle. On the frontend, the "trophy" variant is popular, emphasizing component integration tests (Testing Library).
41. What is a headless component in terms of patterns?
Correct answer: Logic separated from markup and styles
A hook or component provides state and handlers (
useCombobox, Radix primitives), while the app controls markup and styles. It's separation of concerns and OCP: the look changes without changing the logic.42. Which pattern is used in component "slots" (
<Card header={...} footer={...}>)?Correct answer: Composition via props: a skeleton plus passed-in content
Slots (
children, named props with JSX) let you extend a component without adding a flag for every case. It's a direct application of "composition over inheritance" and OCP.43. What is a higher-order function in terms of patterns?
Correct answer: A function that takes or returns a function
map,filter,debounce,memoizeand HOCs are all higher-order functions. In JS, many classic patterns are expressed this way, without classes or hierarchies.44. How are event delegation and the Flyweight pattern related?
Correct answer: One shared handler instead of thousands of identical ones
A handler on the parent is shared by all child elements, and the unique state (which element) comes from
event.target- the Flyweight's extrinsic state. This saves memory and initialization time for large lists.45. How is
useReducerclose to the State pattern?Correct answer: Transitions in one place: new state = f(current, action)
A reducer is a state machine's transition function. You can forbid invalid transitions (ignore
submitin theloadingstate). For complex scenarios, explicit state machines (XState) are used.46. Which pattern does
React.memoor amemoize(fn)function implement?Correct answer: A caching Proxy/Decorator: the wrapper returns the previous result
The wrapper has the same interface and intercepts the call: if the inputs haven't changed, it returns the stored result. A caching proxy is a classic application of the Proxy pattern.
47. When should you extract an abstraction, according to the "rule of three"?
Correct answer: When similar code shows up for the third time
Two cases are often similar by accident, while the third shows what's truly common. The rule helps balance DRY and YAGNI.
48. Which pattern does the Proxy object in Vue 3 or MobX implement for reactivity?
Correct answer: Proxy + Observer: reads register a dependency, writes notify
The
gettrap remembers which effect or component read the property, and thesettrap notifies subscribers of the change. This gives fine-grained reactivity without manual subscriptions. Signals are built on the same principle.49. What is an "anemic model", and why is it criticized?
Correct answer: Objects are just data; the logic lives separately in services
Fowler calls it an anti-pattern in OOP: data and the rules for changing it are separated, so invariants are easy to break. On a functional-style frontend, "data + pure functions side by side in one module" is a reasonable compromise, as long as the rules are concentrated in one place.
50. How does a DI container (Angular, InversifyJS) differ from passing dependencies by hand?
Correct answer: The container creates objects and resolves the dependency graph from configuration
The container registers providers and, on request, assembles an object with all its dependencies, managing lifetimes (singleton, per request, per component). React projects usually make do with Context and factories, without a container.
51. How does Parallel Change (expand/contract) help change a widely used function signature?
Correct answer: Add the new version beside the old, then migrate
Each step is small and deployable. It also works for API fields and database columns.
52. What is Branch by Abstraction?
Correct answer: Swapping implementations behind an abstraction
It allows large replacements (e.g. a charting library) without long-lived branches, often combined with a feature flag.
53. What is the Humble Object pattern?
Correct answer: Keeping hard-to-test code as thin as possible
In React, a hook or pure function holds the logic, and the component just renders - so most logic is tested without the DOM.
54. Why wrap an external payment SDK in your own Gateway?
Correct answer: To isolate its API behind your own interface
The rest of the app talks in your domain terms (
charge(order)), not the vendor's types and quirks.55. What problem does Unit of Work solve, e.g. in an editable spreadsheet-like table?
Correct answer: It tracks changes and commits them together
Batching changes allows one request, all-or-nothing saves and easy discard of unsaved edits.
56. What does the Specification pattern give you for complex filters?
const isEligible = and(isActive, or(isPremium, hasOrdersOver(3)));Correct answer: Small named predicates that can be combined
Business rules become readable building blocks instead of one long condition copied in several places.
57. Why add jitter to exponential backoff when retrying requests?
Correct answer: So clients don't retry in synchronized waves
Randomized delays spread the load. Also cap the number of retries and retry only safe or idempotent operations.
58. How do you prevent two users from silently overwriting each other's edits of the same record?
Correct answer: Optimistic concurrency with a version or ETag
On conflict the UI can show a diff or reload the latest data. HTTP supports this with
If-Matchand412 Precondition Failed.59. What is the Result (Either) pattern for error handling?
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };Correct answer: Returning success or failure as a value
Expected failures (validation, "not found") become explicit. Truly unexpected bugs can still throw.
60. How can composition avoid prop drilling without Context?
<Layout sidebar={<UserMenu user={user} />}>{children}</Layout>Correct answer: Pass ready elements down via
childrenor slotsThe component that owns the data renders the deep child directly; layout components just place it.
61. Why did hooks replace most render props and HOCs?
Correct answer: They share logic without wrapper components
Several hooks compose in one function body; several HOCs create nested wrappers that are hard to debug.
62. How are compound components usually implemented in React?
Correct answer: The parent shares state via Context
Context works even when parts are wrapped in other elements, unlike cloning children.
63. What is a polymorphic
asprop?<Button as="a" href="/docs">Docs</Button>Correct answer: A prop that changes the rendered element
Typing it well (props of the chosen element) takes generics; libraries like Radix use an
asChildvariant instead.64. What is the state reducer pattern?
Correct answer: Users pass a reducer that adjusts internal changes
For example, a dropdown can prevent closing on select without the library adding a new prop for every such case.
65. What are prop getters?
const { getInputProps, getItemProps } = useCombobox(...); <input {...getInputProps({ onKeyDown: myHandler })} />Correct answer: Functions returning props to spread
Users control markup while the library guarantees correct accessibility and event wiring.
66. What is the "divergent change" smell?
Correct answer: One module changes for many unrelated reasons
It's the opposite of shotgun surgery and signals mixed responsibilities that should be split.
67. What is "speculative generality"?
Correct answer: Abstractions that nothing actually uses
Unused flexibility costs reading and maintenance time. Add it when a real second use case appears (YAGNI).
68. What are data clumps, and how are they fixed?
function book(start: Date, end: Date, ...) {} function price(start: Date, end: Date, ...) {}Correct answer: Values that always travel together
The new type is a natural home for related behavior like
range.includes(date)orrange.nights.69. How do you safely refactor legacy code without tests?
Correct answer: Write characterization tests first
Characterization tests lock in what the code does today (even bugs). Seams let you inject test doubles.
70. Why do old feature flags become technical debt?
Correct answer: Every flag doubles the possible code paths
Track flags with an owner and an expiry date, and remove release toggles right after a full rollout.
71. What is a collection pipeline?
orders.filter(isPaid).map(toTotal).reduce(sum, 0)Correct answer: A chain of small data transformations
Each step is easy to name and test. For huge data, lazy iterators avoid creating intermediate arrays.
72. What is currying / partial application useful for?
const log = (level) => (message) => console.log(level, message); const warn = log('warn');Correct answer: Fixing some arguments to specialize a function
It pairs well with pipelines and event handlers, e.g.
onClick={select(id)}.73. Why is "Adapter" useful when replacing a date library?
Correct answer: Only the adapter changes when switching libraries
Wrapping wide third-party APIs behind a narrow interface limits how many files a migration touches.
74. Why is the Chain of Responsibility pattern a good fit for validation rules?
Correct answer: Each rule checks one thing and passes control on
The same idea powers middleware stacks; keep each handler focused and the order explicit.
75. Why use the Facade pattern for a complex feature like video upload (chunks, retries, progress)?
Correct answer: Components call one simple API
The UI stays simple and the complex coordination is tested in one place.