跳转到内容

Desegmentation

此内容尚不支持你的语言。

Desegmentation (also known as horizontal slicing or packaging by layer) is a code organization pattern where files are grouped by their technical roles rather than by the business domains they serve. This means code with similar technical functions is stored in the same place, regardless of the business logic it handles.

This approach is popular in meta-frameworks like Next and Nuxt due to its simplicity, as it’s easy to get started and enables features like auto-imports and file-based routing:

  • 文件夹app
    • 文件夹components
      • DeliveryCard.jsx
      • DeliveryChoice.jsx
      • RegionSelect.jsx
      • UserAvatar.jsx
    • 文件夹actions
      • delivery.js
      • region.js
      • user.js
    • 文件夹composables
      • delivery.js
      • region.js
      • user.js
    • 文件夹constants
      • delivery.js
      • region.js
      • user.js
    • 文件夹utils
      • delivery.js
      • region.js
      • user.js
    • 文件夹stores
      • 文件夹delivery
        • getters.js
        • actions.js

This pattern also occurs in FSD codebases, in the form of generic folders:

  • 文件夹features
    • 文件夹delivery
      • 文件夹ui
        • components ⚠️
  • 文件夹entities
    • 文件夹recommendations
      • utils ⚠️

Files can also be a source of desegmentation. Files like types.ts can aggregate multiple domains, complicating navigation and future refactoring, especially in layers like pages or widgets:

  • 文件夹pages
    • 文件夹delivery
      • index.ts
      • 文件夹ui
        • DeliveryCard.tsx
        • DeliveryChoice.tsx
        • UserAvatar.tsx
      • 文件夹model
        • types.ts ⚠️
        • utils.ts ⚠️
      • 文件夹api
        • endpoints.ts ⚠️
pages/delivery/model/types.ts
// ❌ Bad: Mixed business domains in generic file
export interface DeliveryOption {
id: string;
name: string;
price: number;
}
export interface UserInfo {
id: string;
name: string;
avatar: string;
}

While this structure is easy to start with, it can lead to scalability issues in larger projects:

  • Low Cohesion: Modifying a single feature often requires editing files in multiple large folders, such as pages, components, and stores.

  • Tight Coupling: Components can have unexpected dependencies, leading to complex and tangled dependency chains.

  • Difficult Refactoring: It requires additional effort to manually extract code related to a specific domain.

Group all code that relates to a specific domain in one place.

Avoid generic folder names such as types, components, utils, as well as generic file names like types.ts, utils.ts, or helpers.ts. Instead, use names that directly reflect the domain they represent.

Avoid generic file names like types.ts if possible, especially in slices with multiple domains:

  • 文件夹pages
    • 文件夹delivery
      • index.tsx
      • 文件夹ui
        • DeliveryPage.tsx
        • DeliveryCard.tsx
        • DeliveryChoice.tsx
        • UserInfo.tsx
      • 文件夹model
        • delivery.ts
        • user.ts