36 KiB
Refactoring
Code smells and refactoring techniques from refactoring.guru, mapped to this architecture. Use this file when code resists a change, while you fix a bug, and in review. It doesn't explain the smells and techniques. It says what each one looks like here and which layer or file the fix belongs in. Pattern choices are in design-patterns.md and rendering-patterns.md. Names match the source pages: refactoring.guru/smells/ and refactoring.guru/, in kebab-case.
Contents: When and how · Smells that are intended here · Smell catalog · Front-end smells · Techniques used most · Review comments
When and how
A refactor changes the structure of code and keeps its behavior. Here, behavior also covers what the server renders, what the network sees, and the bundle budgets.
- Never put a refactor in the same commit as a behavior change. Separate commits in one PR are fine. Commit the refactor first, so the behavior change reads as a small diff.
- Cover the behavior first: check it by hand on both templates, mobile and desktop, and say so in the PR. Fix a bug you find this way in a commit of its own. Add a unit test only if the repo already has a unit test runner. The stack has none, so adding one needs approval.
- Take small steps. After each one, type-check, lint, and tests pass for the affected projects through Nx:
nx affected -t <targets>(SKILL.md). Never reach green withany, a cast,@ts-expect-error, or a disabled lint rule. - Rename symbols and move files with the TypeScript language service (the editor's rename, Move to file, and import updates on file move), never with text replace. Keep the naming rules while you rename:
use-<page>-page.ts,<feature>Http,*Payload. The language service can't follow strings such as i18n keys, event names, and route paths, so search for those and check each hit, including every locale's resource file. - A cookie or storage key is a contract with the server or with data already on users' devices, so renaming one is a behavior change (lib-cookie.md, lib-local-storage.md).
- A change to a package's public API, such as an island prop or a lib signature, updates every caller in the same PR.
nx affectedthen checks every app that uses it. - To move or rename a whole Nx project, run the Nx move generator (
@nx/workspace:move), then check the project's tags and its subpath entries (package.jsonexports, or thetsconfig.base.jsonpath aliases). - To move a module into another project, such as a route's organism into island, first check that the target's tags allow every import the module makes. island, for example, imports only libs and tools (project-structure.md). Then move the files, export the module from the target's
index.ts(or itsserver.ts, when the module is server-only) and its subpath, and switch every importer to that subpath. Never silence the boundary rule to make a move compile. - A refactor that spans several features or projects is planned work: give it a written plan and its own PR. Bring legacy code into this architecture one feature at a time, in layer order: entities and repositories first, then actions, models, and UI (SKILL.md).
- State in the PR description that behavior doesn't change, and how you checked: the check by hand on both templates, and the first-load JS of key routes.
Some moves that look safe change behavior here:
- Hoisting a call to module scope.
getEnv(), a repository, a cache,cookie, orstoragethen runs at import time, which can be before bootstrap or, forcookieandstorage, on the server. On the server, the value it produces is shared by every request (b2c-b2b.md). - Moving code across a
'use client'boundary, or importing from a root barrel instead of a subpath. The client bundle changes, so compare the first-load JS of key routes fromnext buildbefore and after (b2c-b2b.md). - Lifting state to a parent or into a context. The parent re-renders its subtree on each change, and a context re-renders every consumer, so check the INP of the heaviest interaction.
- Extracting a component inside another component's body. It becomes a new component type on every render, so React remounts it and drops its state. Define extracted components at module level.
- Reshaping data that outlives the code: a persisted store's state, which users' devices still hold (bump
versionand addmigrate, as in code-patterns.md), or an event's payload, which listeners in other features and integrations read. - Changing a query key's shape. Invalidation matches keys by prefix, and a part finds its hydrated server data only under the exact key the server used. Change the key factory in the repository's
constants.ts, never the call sites (code-patterns.md).
A component that fetches, holds state, and renders is the most common case. Split it in this order, with a green run after each step:
- Record its behavior by hand on both templates.
- Move its state, effects, and handlers into a part model (
use-<page>-<part>-part.ts) as they are, and leave the component presentational. - Move the request into a repository method on the feature's client, with its types, mapper, and query key, and read it through
useQueryin the model. When the first paint or search engines need the data, read it on the server through a cache incaches/instead, and pass it as props or prefetch it for query hydration (b2c-b2b.md). The HTTP lib and the query cache change retries, errors, and caching, so this step changes behavior: give it its own commit and test the error path. - In another behavior commit, add what the rules require and the code lacked, such as a same-size skeleton and a part boundary (error-handling.md).
When to refactor:
- Before a feature the code resists: reshape the code until the feature is a small, obvious edit, then make that edit.
- While fixing a bug, in the layer that owns the fault (SKILL.md), and only as far as the fix needs.
- In review (see Review comments).
- At the third duplication, not the second (the rule of three), because by then the copies show what actually varies. island is the exception: a component that needs a second style gets an island variant at once, never a copy (SKILL.md).
Refactor only the code the change touches, unless the plan says otherwise. Record other smells you notice as debt in the PR's trade-offs note.
When not to refactor:
- Code that is about to be deleted or rewritten.
- Generated files, such as the icon sprite and Icomoon's
selection.json. Change their source or their generator instead. - Library code in
node_modules. Wrap it instead (see Incomplete Library Class). - Untested code when there is no time to add a test. Record it as technical debt in the PR instead.
Smells that are intended here
The catalog would flag these, but the architecture requires them, so never "fix" them. When a tool or a reviewer flags one, point to the reason in the last column.
| What you see | Looks like | Why it stays |
|---|---|---|
Types-only entities, *Dto, and *Payload |
Data Class | The types carry the back-end contract and the UI's shape; mappers, models, and actions do the work |
A mapper that copies fields unchanged, or *Args and *Dto (or *ResponseDto and *Payload) with the same fields |
Duplicate Code | The mapper is where a back-end change stops, so no *Dto reaches the UI |
Named re-exports in every index.ts and server.ts |
Middle Man | They give each module a subpath and keep server-only code out of client bundles. Never collapse them into export * |
http.extend({}) in a feature that needs nothing special |
Lazy Class | Every feature has the same shape, and moving one to its own service is a one-line change (lib-http.md) |
| A cache that wraps one repository call | Middle Man | Every server reader in the request shares one call (b2c-b2b.md) |
| A thin page entry | Middle Man | The entry picks the template and hands it data from the model or the caches, so the logic stays there |
One-line selector hooks such as useCurrentUser |
Lazy Class | They hide the store's shape and keep each subscription small |
| Compound components that read their root's private context | Inappropriate Intimacy | The coupling stays inside one organism, and outside code sees only the compound API |
| A mobile and a desktop template per route | Parallel Inheritance Hierarchies | The server picks one, so only that view's code ships. This holds only while both templates render from the same models and hold no logic of their own |
| A same-size skeleton beside every part that loads on its own | Parallel Inheritance Hierarchies | It keeps the layout still while the part loads, so nothing shifts or flickers |
A new endpoint that touches types.ts, mappers.ts, constants.ts, the repository, and index.ts |
Shotgun Surgery | It is the fixed recipe. Scaffold it with the repo's Nx generator when it has one |
The { emit } and { signal } options, and an event that nothing listens to yet |
Speculative Generality | Actions can run other actions without double events, TanStack Query cancels stale reads, and new listeners never touch the action |
State styles that no page uses yet, such as loading or selected |
Speculative Generality | island builds every state into the component, so no page can forget one (SKILL.md) |
| A page model plus one part model per part that loads or changes on its own | Shotgun Surgery | Each part owns its data and form, and the page model owns only what the parts share, such as the current step |
A <Suspense> and a PartBoundary around each part that loads on its own |
Duplicate Code | One shared boundary would let a slow or failing part block the others |
Smell catalog
Every smell in refactoring.guru's smell catalog, in its groups. Size thresholds, such as the 80 lines below, are guides, not rules. Before you act on a row, check Smells that are intended here.
Bloaters
| Smell | Signal in this codebase | Refactor to |
|---|---|---|
| Long Method | A model hook over about 80 lines; a component that fetches, holds state, and renders; one useEffect that does several jobs |
Extract Method: part models (use-<page>-<part>-part.ts), functions in mappers.ts or shared/utils/, private components in the organism's components/, and one effect per job |
| Large Class | One store that holds several domains; a page model that owns every part's data and form; an organism with many modes and optional props | Extract Class: one store per feature or domain, one part model per part, or a compound component with slots (design-patterns.md) |
| Primitive Obsession | Statuses and roles typed as string; query keys, event names, route paths, and storage keys written as literals at call sites |
Replace Type Code with Class: a union in entities/<entity>/types.ts, like OrderStatus. Replace Magic Number with Symbolic Constant: the owning constants.ts, like productKeys, AUTH_EVENTS, and ROUTES |
| Long Parameter List | A repository method or action with several positional parameters; a component with many flat props, often style flags such as isCompact and hideIcon |
Introduce Parameter Object: the endpoint's *Args, with options last. For a component: one cva variant instead of style flags, children or slots, or two components when a flag switches behavior (Replace Parameter with Explicit Methods) |
| Data Clumps | page, pageSize, sort, and filters passed together through models, query keys, and requests; the same address fields in several forms |
Introduce Parameter Object: one *Args type such as ListProductsArgs, which the model builds once and passes whole to the query key and the repository. For forms: one valibot object schema in shared/validations/ |
Object-orientation abusers
| Smell | Signal in this codebase | Refactor to |
|---|---|---|
| Alternative Classes with Different Interfaces | Two components for the same job with different props (onClose and onDismiss); two repositories that name one operation differently (fetchAll and list) |
Rename Method to one vocabulary, then keep one island component with a variant (Parameterize Method) |
| Refused Bequest | A props type that extends a base type or ComponentPropsWithRef<'input'> but neither uses nor forwards most of it (an island atom that spreads the rest onto its native element is fine, as in code-patterns.md); a *Payload declared as its *ResponseDto plus extra fields, which hands every server field to the UI |
Replace Inheritance with Delegation: Pick the props the component uses, and declare the *Payload in full so the mapper builds it |
| Switch Statements | The same switch or if chain on a status, role, or kind in several components, for labels, colors, icons, or allowed actions |
Replace Conditional with Polymorphism: one Record keyed by the union in the feature's constants.ts, a cva variant in island, or one exhaustive switch (design-patterns.md) |
| Temporary Field | State that means something in one mode only, such as editDraft that is null unless editing, or uploadProgress outside an upload |
Replace Type Code with State/Strategy: a discriminated union such as { status: 'editing'; draft: ProductDraft } | { status: 'viewing' }. Move Field into the part model that uses it |
Change preventers
| Smell | Signal in this codebase | Refactor to |
|---|---|---|
| Divergent Change | One file edited for unrelated reasons: a catch-all shared/utils/helpers.ts, a page model that changes for every part, an island component with branches for one page |
Extract Class by reason to change: one util per file, one part model per part. Move Method page-only code into that route's organisms/, and give island a variant or a slot instead |
| Parallel Inheritance Hierarchies | Each new status or entity kind needs a matching card, row, and form file; a route's mobile and desktop templates each hold their own logic or data calls | Move Method: the logic into the page or part model, so both templates render one model. When a per-kind split must stay, keep one Record per concern keyed by the union, so a missing member fails type-check |
| Shotgun Surgery | One business rule spread across components, validations, and mappers; a cross-cutting concern, such as a header, a log line, or an analytics call, repeated in every repository or action | Move Method and Move Field to one owner: the rule into a model, a util, or a validation; a request concern into the feature's http.ts (headers or a feature-only interceptor), or into an interceptor on the root client in bootstrap when every feature needs it (lib-http.md); an analytics call into a listener on the action's event, subscribed in the AppShell. Inline Class merges scattered fragments |
Dispensables
| Smell | Signal in this codebase | Refactor to |
|---|---|---|
| Comments | A comment that explains what a JSX block, an effect, or a condition does | Extract Method into a named hook, component, or predicate, or Extract Variable. Keep comments that explain why, such as a back-end quirk or a browser bug |
| Duplicate Code | Copied JSX or class strings; the same mapping in two mappers; the same query and cache update in several models; a page and its generateMetadata that combine the same caches; the same code in two products |
A copied or restyled island component: an island variant at once. Other copies, at the third one: an island component, a mapper, a shared/utils/ function, or a hook in the owning feature's models/. A server page loader, load-<page>-page.ts, for the page and its metadata (b2c-b2b.md). Parameterize Method when copies differ in one value. Code that two products share moves down to a package, never across to the other product |
| Data Class | The same derivation from a *Payload, such as a display name, a total, or a status flag, repeated in several components |
Move Method: a field the mapper computes, when every consumer needs it and it doesn't depend on the locale; otherwise a selector hook or a util in the owning feature |
| Dead Code | Exports nobody imports, props no caller passes, cva variants and i18n keys nobody uses, and flag branches that always go one way | Delete it, with Remove Parameter for props and arguments. TypeScript's noUnusedLocals and noUnusedParameters find unused locals and parameters, and Find All References finds unused exports. knip automates the export search, but it is outside the stack and needs approval |
| Lazy Class | A wrapper component that only forwards props to one island component; a hook or util with one line and one caller | Inline Class or Inline Method into the caller |
| Speculative Generality | A config-driven component or generic hook with one caller; props, variants, or *Args fields that nobody passes; a wrapper over TanStack Query or zustand in case the library changes |
Inline Class, Inline Method, or Remove Parameter. Add the generality at the third real use |
Couplers
| Smell | Signal in this codebase | Refactor to |
|---|---|---|
| Feature Envy | A model or component that computes from another feature's *Payload fields or another store's raw state, or builds another feature's query keys by hand |
Move Method to the owner of the data: a util or the key factory (such as productKeys), exported through that feature's index.ts, or a selector hook beside the store in stores/<store>/ |
| Inappropriate Intimacy | Imports from another feature's internals (its http.ts, mappers, or repository folders) or from an organism's private components/ and hooks/; two features that import each other |
Import through the owner's index.ts, and let Hide Method keep the rest private, or move the shared piece to island or shared/. Break a cycle by letting one side react to the other's event (Change Bidirectional Association to Unidirectional) |
| Incomplete Library Class | The same work-around for a library repeated at call sites, such as extra classes that work around tailwind-merge dropping a theme token, identical toast.error options, or the same Intl setup |
Introduce Local Extension: a wrapper like cn in island tools/; a shared helper that imports no other project, such as the Intl formatters, in packages/tools; a framework-agnostic library of the kinds project-structure.md lists for packages/libs, such as http, cookie, or regex, in packages/libs. Introduce Foreign Method: one helper in shared/utils/, like applyServerErrors |
| Message Chains | Deep paths in components, such as the selector (state) => state.session?.user.role repeated across components, or order.customer.address.city in JSX |
Hide Delegate: a selector hook beside the store, such as useCurrentUser, and a flatter *Payload built by the mapper |
| Middle Man | A services/ or api/ layer between models and repositories; a hook or organism that only forwards to one other |
Remove Middle Man: call the repository or render the component directly |
Front-end smells
The catalog doesn't name these, but this stack has them. Each line gives the smell, the fix, and the rule behind it.
- Props passed down more than two levels → the part reads its own data from its part model or a selector hook, or the parent passes
children(SKILL.md). - State derived from other state, or synced with it, in
useEffect→ derive it during render from props, the query, or a selector. Reset state with akeyonly on a subtree that isn't visible across the change, such as a dialog's form when the dialog opens (SKILL.md). - Server state copied into zustand or component state → read it from the query cache through the model (SKILL.md).
- Several booleans for one flow → one status union with explicit states (SKILL.md).
fetch, HTTP calls, or data loading in a component or itsuseEffect→ a repository method on the feature's client, read throughuseQueryin the model (lib-http.md); first-paint data goes through a cache on the server (b2c-b2b.md).- Array-index or random keys in a dynamic list → stable ids from the
*Payload(SKILL.md). - One large context → one context per concern.
- A component that subscribes to a whole store → a selector for the smallest slice it renders (code-patterns.md).
- Hard-coded text, colors, or sizes → i18n keys and semantic tokens (code-patterns.md).
'use client'on a page, layout, or template → only on the interactive leaf, driven by its part model (b2c-b2b.md).- Business logic in components → the model, action, mapper, or util that owns it (SKILL.md).
- Viewport checks choosing layouts → the template the server picks (b2c-b2b.md).
- A server render that depends on auth (a session read, auth cookies forwarded, a variant picked on the server, or a page that needs a logged-in user rendered on the server) → a browser part, or a page behind the
AuthGuard, that renders its skeleton until the auth store knows the viewer (rendering-patterns.md). Leave it when the developer explicitly asked for it and the plan or a decision records it. - The guest variant shown while the viewer is still unknown → the same-size skeleton while the auth store's
statusis'unknown'(rendering-patterns.md). - A
<Suspense>boundary or'use client'added to keep a part out of the server render → a technique from rendering-patterns.md's "What keeps a part out of the server HTML": browser-only state that renders the skeleton,next/dynamicwithssr: false, orLoadOnVisible(rendering-patterns.md). - Cookie or storage reads during render → an effect or an event handler, or
cookies()on the server passed down as a prop (lib-cookie.md, lib-local-storage.md). - Module-scope data on the server → React
cache(), props, or the per-requestQueryClient(b2c-b2b.md). - A page, loader, or server component that calls a repository directly → a cache, so every reader in the request shares one call (b2c-b2b.md).
- A cache called with an object argument, or created inside a component → primitive arguments, and
cache()defined at module level (b2c-b2b.md). - A store written during server render → props or the query cache, or a store created per request (b2c-b2b.md).
useSuspenseQueryon a query the server didn't prefetch →useQuerywith a skeleton (b2c-b2b.md).- A mutation that leaves stale queries, or relies on
staleTimeexpiring → set the detail, patch the lists, and invalidate them (code-patterns.md); also callrouter.refresh()when the change shows in server-rendered content (b2c-b2b.md). - Query retries on top of the HTTP lib's retries → queries don't retry;
configs/react-query.tssetsretry: false(lib-http.md). - A refetch that swaps content for a spinner → keep the data and show
isFetchinginline (b2c-b2b.md). - A
catchthat swallows the error or shows a hand-madetoast.error→ in a form,applyServerErrors; elsewhere,showActionError, which adds the hint or reference ID and the retry the cause allows (code-patterns.md). - An
isErrorbranch in a component, or a toast for a failed read → let the read throw to its part boundary, which shows the fallback or thenot-foundandno-accessempty states (error-handling.md). handleError, or a report to the tracker, in a repository, an action, or acatchthat rethrows → call it once, where the error stops: the fallback,showActionError,QueryCache.onError, oronRequestError(error-handling.md).- A server read whose 404 or 403 reaches the browser as a digest → read it through
readOnServerand decide on the server (error-handling.md). - An
ABORTEDerror shown as a toast or an error state → ignore it (lib-http.md). - Toasts, navigation, business logic, or store writes in an HTTP interceptor → a model or an action (lib-http.md).
- An action that runs another action as one of its steps, emits its own event, and still lets the inner action emit → pass
{ emit: false }to the inner action, so listeners hear one event per operation (code-patterns.md). - An event subscription in a component or at module top level, or one without an unsubscribe → subscribe once in an effect of the
AppShelland unsubscribe in its cleanup (code-patterns.md). process.envoutside the app'senv/→ the app's env, or the project'sgetEnv()inside a function (lib-env.md).
Many of these show up in a plain text search, which makes a quick first pass in review: export *, 'use client' in a page.tsx or layout.tsx, process.env outside env/, fetch( outside the HTTP lib, and key={index}.
Techniques used most
Grouped as in refactoring.guru's technique catalog. Each line says how the technique looks in this codebase.
Composing methods
- Extract Method: extract a function, a hook, or a component. Logic goes to a model hook, a mapper, or a util, markup to a private component, and each job of a long effect to its own effect.
- Inline Method: fold a one-line wrapper hook or util back into its only caller.
- Extract Variable: name a condition before the JSX, or return it from the model:
const canEdit = canUpdate && !order.isLocked;. - Replace Temp with Query: derive a value during render from props, the query, or a selector instead of mirroring it in
useState. - Remove Assignments to Parameters: never reassign or mutate an argument. Mappers build a new object, interceptors return a new config (lib-http.md), and props and query data stay read-only.
- Substitute Algorithm: replace hand-built date and number formatting with
Intl, using the locale and time zone the server chose (b2c-b2b.md).
Moving features between objects
- Move Method and Move Field: move code to the layer that owns it, following the layer order in project-structure.md. Requests go to a repository, locale-free shaping to a mapper, operations with side effects beyond the request to an action, orchestration to a model, and shared UI to island. State moves down to the component or part model that uses it, or up to the page model when parts share it.
- Extract Class: extract a module, a hook, or a component, such as one store per domain, part models out of a page model, or private components out of an organism.
- Inline Class: merge a module that does almost nothing into its only user.
- Hide Delegate: selector hooks beside the store, such as
useCurrentUser, so components never walk the store's shape. - Remove Middle Man: delete pass-through hooks, wrappers, and layers, except the intended ones.
- Introduce Foreign Method: one helper for what a library lacks, in
shared/utils/, likeapplyServerErrorsfor react-hook-form andHttpError. - Introduce Local Extension: a wrapper module over a library, like
cnover clsx and tailwind-merge in islandtools/. A shared helper that imports no other project goes inpackages/tools, and a framework-agnostic library of the kinds project-structure.md lists forpackages/libsgoes there.
Organizing data
- Replace Magic Number with Symbolic Constant: name it in the owning
constants.ts, likeRELATED_PRODUCTS_LIMIT. A color, size, or breakpoint becomes a token in islandtheme.cssinstead. - Replace Type Code with Class: a string-literal union in the entity, like
OrderStatus, or anas constobject when code needs the values at runtime. - Replace Type Code with Subclasses: a discriminated union with one component per member, chosen through one map.
- Replace Type Code with State/Strategy: a discriminated-union status for a flow, and a
Recordof handlers for behavior that varies per member. - Encapsulate Collection: only the store's actions change its arrays. Type the arrays
readonlyin the store'stypes.ts. For the persisted cart store in code-patterns.md, its state becomes the one below. As in code-patterns.md, the path is relative toplatforms/<app>/src/.
stores/cart/types.ts
import type { CartItemPayload } from '../../features/cart';
export type CartState = {
items: readonly CartItemPayload[];
addItem: (item: CartItemPayload) => void;
clear: () => void;
};
Outside the store, useCartStore.getState().items.push(item) no longer compiles. Inside set, state.items.push(item) still does, because immer's draft type drops readonly.
Simplifying conditional expressions
- Decompose Conditional: move each branch of a large conditional JSX block into a named private component, and the condition into a predicate the model returns.
- Consolidate Conditional Expression: one named boolean from the model, such as
canSubmit, instead of the same chain of checks in several places. - Replace Nested Conditional with Guard Clauses: early returns right after the component's hook calls for pending, error, and empty. Guard on
isPending, never onisFetching, so a refetch keeps the content. - Replace Conditional with Polymorphism: a
Recordmap, a cva variant, or a discriminated union with one exhaustiveswitch(design-patterns.md), never a class hierarchy. - Introduce Null Object: use it only in mappers, for a list the server may leave out (
items: dto.items ?? []), so the UI never checks fornull. Never give a query an empty*PayloadasinitialData, because the cache treats it as real, fresh data and skips the fetch untilstaleTimeends. Never give one asplaceholderDataeither, because the UI would show the empty state while loading. Never replacesession: nullwith a guest user, because the guards send anullsession to login. - Introduce Assertion: parse data you don't control with a valibot schema instead of an
ascast, such asstorage.getJSONresults.
Simplifying method calls
- Introduce Parameter Object: the endpoint's
*Argstype. Repositories take(args, { signal })and actions(args, { emit }), so a new field changes one type instead of every call. - Preserve Whole Object: pass the
*Payloaditem instead of several of its fields, between server components and inside a module. At a client boundary, pass only what the leaf needs, because props are serialized into the page (b2c-b2b.md). - Replace Parameter with Method Call: a part gets its own data from its part model or a selector hook instead of props passed through several levels. What the page model shares still reaches the parts as props.
- Parameterize Method: merge near-identical components into one with a cva variant.
- Replace Parameter with Explicit Methods: split a component whose boolean prop switches its behavior into two components.
- Remove Parameter: delete a prop or
*Argsfield that nobody passes. The{ emit }and{ signal }options stay. - Separate Query from Modifier: reads live in models as queries. A mutation that only sends the request runs through
useMutationin the model, and an operation with side effects beyond the request (store writes, storage, follow-up calls, its event) lives in an action. Render, selectors, mappers, and repository read methods never change state. - Hide Method: keep internals out of
index.ts. A feature never exports itshttp.tsclient or any*Dto, and an organism never exports itscomponents/orhooks/. The one exception is a compound component, whoseindex.tsre-exports its named parts (design-patterns.md). - Replace Error Code with Exception: repositories throw the lib's
HttpErrorand never returnnull,false, or{ error }for a failure. Actions let it propagate. For an action, the model catches it:applyServerErrorsin a form,showActionErrorelsewhere. A failed read throws to its part or page boundary, which shows thenot-foundorno-accessempty state for 404 and 403 and a fallback with Try again otherwise (error-handling.md). The one place that turns errors back into values isreadOnServeron the server, because a page must decide betweennotFound(), an empty state, and a boundary before it renders.
Dealing with generalization
- Extract Interface: a type for a contract with more than one implementation or a test double, like
CookieAdapterAbstraction(lib-cookie.md). - Replace Inheritance with Delegation: compose instead of extending. Use an island component through its
children, slots, compound parts, or a new island variant, never a feature-level wrapper that restyles it. Build props types from existing ones withPickandOmit.
The class-hierarchy techniques rarely apply, because the codebase avoids inheritance. Use these instead:
- Pull Up Method and Pull Up Field: a shared hook, util, or props type.
- Push Down Method and Push Down Field: move the code into the one component, or the field into the one union member, that uses it.
- Extract Superclass and Extract Subclass: a shared hook or base component that others compose, and a specialized component that composes the general one.
- Collapse Hierarchy: one component with a variant instead of near-identical ones.
- Form Template Method: a template with slots, or a hook that takes step callbacks.
Review comments
Phrase a refactoring finding in the review format from SKILL.md: name the smell, or the rule when one is broken; show the problem with its file and its cost; and propose the technique with its target layer or file.
- A smell is a suggestion with a rationale. It blocks a merge only when it also breaks a rule on that section's blocking list, such as a boundary or layer violation or a stale cache after a mutation. Then lead with the rule, mark it blocking, and name the smell in the body.
- In a feature PR, raise smells only in the code the PR touches, and suggest a follow-up PR for the rest.
- Never flag the smells that are intended here.
Switch Statements (suggestion):
OrderRow.tsx,OrderCard.tsx, andOrderHeader.tsxeach switch onorder.statusto pick a label and a badge color, so a new status needs three edits and nothing checks that all three were made. Replace Conditional with Polymorphism: oneRecordkeyed byOrderStatus, holding the label key and the Badge variant, infeatures/orders/constants.ts(likeORDER_STATUS_BADGESin design-patterns.md), and island'sBadgevariantfor the color. A new status then fails type-check until the map covers it.
Features import each other only through index.ts (blocking):
features/cart/models/cart/use-cart-page.tsimportscatalogHttpand the catalog mappers to load the cart's products itself. That is Inappropriate Intimacy: the request skips catalog's repository, and any change inside catalog can break the cart. Move Method: addlistByIdsto the repository infeatures/catalog/repositories/products/, and importproductsRepositorythroughfeatures/catalog/index.ts.