# 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](design-patterns.md) and [rendering-patterns.md](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 ` ([SKILL.md](../SKILL.md#4-workflow)). Never reach green with `any`, 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.ts`, `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-cookie.md#keys), [lib-local-storage.md](lib-local-storage.md#keys)). - 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 affected` then 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.json `exports`, or the `tsconfig.base.json` path 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](project-structure.md#nx-tags-and-boundaries)). Then move the files, export the module from the target's `index.ts` (or its `server.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](../SKILL.md#4-workflow)). - 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`, or `storage` then runs at import time, which can be before bootstrap or, for `cookie` and `storage`, on the server. On the server, the value it produces is shared by every request ([b2c-b2b.md](b2c-b2b.md#server-and-client-entries)). - 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 before and after, measured as [b2c-b2b.md](b2c-b2b.md#targets) describes. - 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 `version` and add `migrate`, as in [code-patterns.md](code-patterns.md#persisted-store)), 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](code-patterns.md#repository)). 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: 1. Record its behavior by hand on both templates. 2. Move its state, effects, and handlers into a part model (`use---part.ts`) as they are, and leave the component presentational. 3. Move the request into a repository method on the feature's client, with its types, mapper, and query key, and read it through `useQuery` in the model. When the first paint or search engines need the data, read it on the server through a cache in `caches/` instead, and pass it as props or prefetch it for query hydration ([b2c-b2b.md](b2c-b2b.md#data-flow)). 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. 4. 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](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](../SKILL.md#4-workflow)), 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](../SKILL.md#3-architecture-rules)). A route's organism that a second route needs also moves at once, never as a copy: to island when it's domain-free, or to the platform's `screens/`, at the nearest route level both share, when it knows a domain ([project-structure.md](project-structure.md#choosing-where-a-component-goes)). 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](lib-http.md#root-and-feature-clients)) | | A cache that wraps one repository call | Middle Man | Every server reader in the request shares one call ([b2c-b2b.md](b2c-b2b.md#data-flow)) | | 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 per request, so the markup matches on hydration and nothing shifts. 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](../SKILL.md#3-architecture-rules)) | | 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 `` 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---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](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//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](code-patterns.md#island-component-module)); 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](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](lib-http.md#interceptors)); 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.ts`, for the page and its metadata ([b2c-b2b.md](b2c-b2b.md#server-and-client-entries)). 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//` | | 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](project-structure.md#libs-integrations-and-tools-packages) 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](../SKILL.md#3-architecture-rules)). - 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 a `key` only on a subtree that isn't visible across the change, such as a dialog's form when the dialog opens ([SKILL.md](../SKILL.md#3-architecture-rules)). - Server state copied into zustand or component state → read it from the query cache through the model ([SKILL.md](../SKILL.md#3-architecture-rules)). - Several booleans for one flow → one status union with explicit states ([SKILL.md](../SKILL.md#3-architecture-rules)). - `fetch`, HTTP calls, or data loading in a component or its `useEffect` → a repository method on the feature's client, read through `useQuery` in the model ([lib-http.md](lib-http.md#root-and-feature-clients)); first-paint data goes through a cache on the server ([b2c-b2b.md](b2c-b2b.md#data-flow)). - Array-index or random keys in a dynamic list → stable ids from the `*Payload` ([SKILL.md](../SKILL.md#3-architecture-rules)). - 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](code-patterns.md#store)). - Hard-coded text, colors, or sizes → i18n keys and semantic tokens ([code-patterns.md](code-patterns.md#tokens-and-tailwind-wiring)). - `'use client'` on a page, layout, or template → only on the interactive leaf, driven by its part model ([b2c-b2b.md](b2c-b2b.md#rendering)). - Business logic in components → the model, action, mapper, or util that owns it ([SKILL.md](../SKILL.md#3-architecture-rules)). - Viewport checks choosing layouts → the template the server picks ([b2c-b2b.md](b2c-b2b.md#rendering)). - 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](rendering-patterns.md#auth-dependent-ui)). 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 `status` is `'unknown'` ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)). - A `` 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/dynamic` with `ssr: false`, or `LoadOnVisible` ([rendering-patterns.md](rendering-patterns.md#choosing-where-a-part-loads)). - 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-cookie.md#browser-only), [lib-local-storage.md](lib-local-storage.md#browser-only)). - Module-scope data on the server → React `cache()`, props, or the per-request `QueryClient` ([b2c-b2b.md](b2c-b2b.md#no-server-cache)). - 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](b2c-b2b.md#data-flow)). - A cache called with an object argument, or created inside a component → primitive arguments, and `cache()` defined at module level ([b2c-b2b.md](b2c-b2b.md#data-flow)). - A store written during server render → props or the query cache, or a store created per request ([b2c-b2b.md](b2c-b2b.md#state-and-auth)). - `useSuspenseQuery` on a query the server didn't prefetch → `useQuery` with a skeleton ([b2c-b2b.md](b2c-b2b.md#data-flow)). - A mutation that leaves stale queries, or relies on `staleTime` expiring → set the detail, patch the lists, and invalidate them ([code-patterns.md](code-patterns.md#mutation-with-a-valid-cache)); also call `router.refresh()` when the change shows in server-rendered content ([b2c-b2b.md](b2c-b2b.md#no-server-cache)). - Query retries on top of the HTTP lib's retries → queries don't retry; `configs/react-query.ts` sets `retry: false` ([lib-http.md](lib-http.md#retry)). - A refetch that swaps content for a spinner → keep the data and show `isFetching` inline ([ui-rules.md](ui-rules.md#stability)). - A `catch` that swallows the error or shows a hand-made `toast.error` → in a form, `applyServerErrors`; elsewhere, `showActionError`, which adds the hint or reference ID and the retry the cause allows ([code-patterns.md](code-patterns.md#validation-model-and-server-errors)). - An `isError` branch in a component, or a toast for a failed read → let the read throw to its part boundary, which shows the fallback or the `not-found` and `no-access` empty states ([error-handling.md](error-handling.md#reads)). - `handleError`, or a report to the tracker, in a repository, an action, or a `catch` that rethrows → call it once, where the error stops: the fallback, `showActionError`, `QueryCache.onError`, or `onRequestError` ([error-handling.md](error-handling.md#reporting)). - A server read whose 404 or 403 reaches the browser as a digest → read it through `readOnServer` and decide on the server ([error-handling.md](error-handling.md#b2cb2b-server)). - An `ABORTED` error shown as a toast or an error state → ignore it ([lib-http.md](lib-http.md#abort)). - Toasts, navigation, business logic, or store writes in an HTTP interceptor → a model or an action ([lib-http.md](lib-http.md#interceptors)). - 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](code-patterns.md#action)). - An event subscription in a component or at module top level, or one without an unsubscribe → subscribe once in an effect of the `AppShell` and unsubscribe in its cleanup ([code-patterns.md](code-patterns.md#action)). - `process.env` outside the app's `env/` → the app's env, or the project's `getEnv()` inside a function ([lib-env.md](lib-env.md#project-env)). - A hard-coded env value (an address, key, third-party ID, or flag), a fallback such as `?? 'http://localhost:3000'`, a schema default, or a `.env` file outside an app → a required variable in the app's `.env`, read through the app's env or the project's `getEnv()` ([lib-env.md](lib-env.md#the-apps-env)). - Navigation through `onClick` and `router.push`, a `