code-quality-standards

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Code Quality Standards

代码质量标准

Core principle: Write clean, maintainable code that speaks for itself.
核心原则: 编写无需额外解释的清晰、可维护代码。

When to Use This Skill

何时使用此规范

Always use when:
  • Writing any new code
  • Refactoring existing code
  • Reviewing code before committing
  • Creating functions, variables, or classes
This is mandatory - not optional.
任何时候都必须使用:
  • 编写任何新代码时
  • 重构现有代码时
  • 提交前评审代码时
  • 创建函数、变量或类时
此规范为强制性要求,而非可选规则。

Five Non-Negotiable Rules

五条不可妥协的规则

1. Variable Names Must Be Descriptive, Not IDs

1. 变量命名必须具备描述性,不能仅用ID类缩写

WRONG:
typescript
const id = getUserId();
const val = calculateTotal();
const tmp = data.filter(x => x.active);
const i = items[0];
const user1 = getUser();
const data2 = processData();
const result3 = calculate();
RIGHT:
typescript
const currentUserId = getUserId();
const orderTotal = calculateTotal();
const activeCustomers = data.filter(customer => customer.active);
const firstItem = items[0];
const primaryUser = getUser();
const processedCustomerData = processData();
const finalCalculationResult = calculate();
Key principles:
  • Use full, descriptive names that reveal intent
  • Avoid abbreviations (except universally understood ones like
    url
    ,
    id
    in compound names)
  • Variables should read like English sentences
  • Never use single letters except in tiny scopes (map/filter callbacks)
  • Never use numbers in variable names (e.g.,
    user1
    ,
    data2
    ,
    temp3
    )
  • Be verbose - clarity > brevity
错误示例:
typescript
const id = getUserId();
const val = calculateTotal();
const tmp = data.filter(x => x.active);
const i = items[0];
const user1 = getUser();
const data2 = processData();
const result3 = calculate();
正确示例:
typescript
const currentUserId = getUserId();
const orderTotal = calculateTotal();
const activeCustomers = data.filter(customer => customer.active);
const firstItem = items[0];
const primaryUser = getUser();
const processedCustomerData = processData();
const finalCalculationResult = calculate();
核心原则:
  • 使用完整、具备描述性的命名,明确表达用途
  • 避免缩写(除非是
    url
    、复合名称中的
    id
    这类通用缩写)
  • 变量命名应如同英文语句般易懂
  • 除了map/filter回调这类极小作用域,禁止使用单字母变量
  • 禁止在变量名中使用数字(如
    user1
    data2
    temp3
  • 宁可冗长也要清晰——清晰度优先于简洁性

2. Actual Implementation, Not Placeholders

2. 实现真实功能,而非占位符

WRONG:
typescript
function processOrder(order: Order) {
  // TODO: Implement validation
  // Validate order here
  /* Implementation goes here */
  return true;
}

const handleSubmit = () => {
  // To be implemented
};
RIGHT:
typescript
function processOrder(order: Order): ProcessedOrder {
  if (!order.items || order.items.length === 0) {
    throw new Error('Order must contain at least one item');
  }

  if (order.total <= 0) {
    throw new Error('Order total must be greater than zero');
  }

  const validatedOrder = {
    ...order,
    validatedAt: new Date(),
    status: 'validated',
  };

  return validatedOrder;
}

const handleSubmit = async (formData: FormData) => {
  const validatedData = validateFormData(formData);
  await saveToDatabase(validatedData);
  navigateToSuccessPage();
};
Key principles:
  • Write complete, working implementations
  • No TODO comments for core functionality
  • No placeholder functions
  • No "to be implemented" comments
  • If you write a function, implement it fully
错误示例:
typescript
function processOrder(order: Order) {
  // TODO: Implement validation
  // Validate order here
  /* Implementation goes here */
  return true;
}

const handleSubmit = () => {
  // To be implemented
};
正确示例:
typescript
function processOrder(order: Order): ProcessedOrder {
  if (!order.items || order.items.length === 0) {
    throw new Error('Order must contain at least one item');
  }

  if (order.total <= 0) {
    throw new Error('Order total must be greater than zero');
  }

  const validatedOrder = {
    ...order,
    validatedAt: new Date(),
    status: 'validated',
  };

  return validatedOrder;
}

const handleSubmit = async (formData: FormData) => {
  const validatedData = validateFormData(formData);
  await saveToDatabase(validatedData);
  navigateToSuccessPage();
};
核心原则:
  • 编写完整、可运行的实现
  • 核心功能禁止使用TODO注释
  • 禁止使用占位符函数
  • 禁止使用“待实现”类注释
  • 编写函数时必须完整实现其功能

3. Never Care About Backward Compatibility

3. 无需考虑向后兼容性

WRONG:
typescript
// Keep old function for backward compatibility
function getUser(id: string) {
  return getUserById(id);
}

function getUserById(userId: string) {
  // New implementation
}

// Support both old and new parameter names
function createOrder(params: { id?: string; orderId?: string }) {
  const actualOrderId = params.orderId || params.id;
}
RIGHT:
typescript
// Just use the better name
function getUserById(userId: string) {
  // Implementation
}

function createOrder(orderId: string) {
  // Implementation
}
Key principles:
  • Don't keep deprecated functions
  • Don't support multiple parameter formats
  • Don't add compatibility shims
  • If a name is bad, change it - delete the old one
  • Clean breaks > gradual migration
错误示例:
typescript
// Keep old function for backward compatibility
function getUser(id: string) {
  return getUserById(id);
}

function getUserById(userId: string) {
  // New implementation
}

// Support both old and new parameter names
function createOrder(params: { id?: string; orderId?: string }) {
  const actualOrderId = params.orderId || params.id;
}
正确示例:
typescript
// Just use the better name
function getUserById(userId: string) {
  // Implementation
}

function createOrder(orderId: string) {
  // Implementation
}
核心原则:
  • 保留已废弃函数
  • 禁止支持多种参数格式
  • 禁止添加兼容性垫片
  • 如果命名不佳,直接修改并删除旧命名
  • 彻底重构优于逐步迁移

4. Never Use Lint Suppressions

4. 禁止使用Lint抑制

WRONG:
typescript
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function process(data: any) {
  return data;
}

// biome-ignore lint/suspicious/noExplicitAny: legacy code
function processLegacy(data: any) {
  return data;
}

// @ts-ignore
const result = unsafeOperation();

/* eslint-disable */
function legacyCode() {
  // Bad code here
}
/* eslint-enable */
RIGHT:
typescript
function processUserData(userData: UserData): ProcessedUserData {
  return {
    userId: userData.id,
    userName: userData.name,
    processedAt: new Date(),
  };
}

function performSafeOperation(): OperationResult {
  const validatedInput = validateInput();
  return executeOperation(validatedInput);
}

function modernImplementation(customer: Customer): Invoice {
  const invoiceItems = customer.orders.map(createInvoiceItem);
  return generateInvoice(invoiceItems);
}
Key principles:
  • Fix the code instead of suppressing warnings
  • Type everything properly - no
    any
    , no
    @ts-ignore
  • If the linter complains, there's usually a good reason
  • Write code that passes linting naturally
  • Suppressions = technical debt
  • No
    eslint-disable
    ,
    @ts-ignore
    ,
    biome-ignore
    , or any other suppressions
错误示例:
typescript
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function process(data: any) {
  return data;
}

// biome-ignore lint/suspicious/noExplicitAny: legacy code
function processLegacy(data: any) {
  return data;
}

// @ts-ignore
const result = unsafeOperation();

/* eslint-disable */
function legacyCode() {
  // Bad code here
}
/* eslint-enable */
正确示例:
typescript
function processUserData(userData: UserData): ProcessedUserData {
  return {
    userId: userData.id,
    userName: userData.name,
    processedAt: new Date(),
  };
}

function performSafeOperation(): OperationResult {
  const validatedInput = validateInput();
  return executeOperation(validatedInput);
}

function modernImplementation(customer: Customer): Invoice {
  const invoiceItems = customer.orders.map(createInvoiceItem);
  return generateInvoice(invoiceItems);
}
核心原则:
  • 修复代码而非抑制警告
  • 为所有内容添加正确类型——禁止使用
    any
    、禁止使用
    @ts-ignore
  • 代码检查工具报错通常有合理原因
  • 编写天然符合代码检查规则的代码
  • 抑制规则等同于技术债务
  • 禁止使用
    eslint-disable
    @ts-ignore
    biome-ignore
    或任何其他抑制注释

5. Code Must Pass Biome and TypeScript Checks

5. 代码必须通过Biome和TypeScript检查

WRONG:
typescript
// Code that has type errors
function processData(data) {  // Missing type annotation
  return data.map(item => item.value);  // No type safety
}

// Code that fails Biome checks
const unused = 'variable';  // Unused variable
let x = 1; x = 2;  // Unnecessary let when const would work

// Committing without running checks
// git commit -m "quick fix"
RIGHT:
typescript
// Code with proper types
interface DataItem {
  value: string;
}

function processData(data: DataItem[]): string[] {
  return data.map(item => item.value);
}

// Clean code that passes all checks
const processedResults = calculateResults();
const finalValue = processedResults.total;

// Always verify before committing
// npm run typecheck  ✓
// npm run biome:check  ✓
Key principles:
  • Run
    tsc --noEmit
    or equivalent before committing
  • Run Biome checks before committing
  • Fix all type errors - no
    any
    types
  • Fix all Biome warnings - unused variables, incorrect patterns
  • Never commit code that doesn't pass checks
  • TypeScript strict mode should be enabled
  • All code must be properly typed
Required commands before commit:
bash
undefined
错误示例:
typescript
// Code that has type errors
function processData(data) {  // Missing type annotation
  return data.map(item => item.value);  // No type safety
}

// Code that fails Biome checks
const unused = 'variable';  // Unused variable
let x = 1; x = 2;  // Unnecessary let when const would work

// Committing without running checks
// git commit -m "quick fix"
正确示例:
typescript
// Code with proper types
interface DataItem {
  value: string;
}

function processData(data: DataItem[]): string[] {
  return data.map(item => item.value);
}

// Clean code that passes all checks
const processedResults = calculateResults();
const finalValue = processedResults.total;

// Always verify before committing
// npm run typecheck  ✓
// npm run biome:check  ✓
核心原则:
  • 提交前运行
    tsc --noEmit
    或等效命令
  • 提交前运行Biome检查
  • 修复所有类型错误——禁止使用
    any
    类型
  • 修复所有Biome警告——如未使用变量、不正确的代码模式
  • 禁止提交未通过检查的代码
  • 应启用TypeScript严格模式
  • 所有代码必须添加正确类型
提交前必须执行的命令:
bash
undefined

TypeScript type check

TypeScript type check

npm run typecheck
npm run typecheck

or

or

tsc --noEmit
tsc --noEmit

Biome check (lint + format)

Biome check (lint + format)

npx biome check .
npx biome check .

or

or

npm run biome:check
undefined
npm run biome:check
undefined

Hardcoded Values - Never Use Them

禁止使用硬编码值

WRONG:
typescript
if (user.role === 'admin') { }
const timeout = 5000;
const apiUrl = 'https://api.example.com';
const maxRetries = 3;
RIGHT:
typescript
const USER_ROLE_ADMIN = 'admin';
const REQUEST_TIMEOUT_MILLISECONDS = 5000;
const API_BASE_URL = process.env.API_BASE_URL;
const MAXIMUM_RETRY_ATTEMPTS = 3;

if (user.role === USER_ROLE_ADMIN) { }
Key principles:
  • Extract all magic numbers and strings to named constants
  • Use SCREAMING_SNAKE_CASE for constants
  • Constants should have descriptive, verbose names
  • Environment-specific values come from env vars
  • The constant name should explain what the value means
错误示例:
typescript
if (user.role === 'admin') { }
const timeout = 5000;
const apiUrl = 'https://api.example.com';
const maxRetries = 3;
正确示例:
typescript
const USER_ROLE_ADMIN = 'admin';
const REQUEST_TIMEOUT_MILLISECONDS = 5000;
const API_BASE_URL = process.env.API_BASE_URL;
const MAXIMUM_RETRY_ATTEMPTS = 3;

if (user.role === USER_ROLE_ADMIN) { }
核心原则:
  • 将所有魔数和字符串提取为命名常量
  • 常量使用SCREAMING_SNAKE_CASE命名法
  • 常量命名应具备描述性、清晰明确
  • 环境相关值来自环境变量
  • 常量名称应解释值的含义

Naming Conventions

命名规范

Variables

变量

typescript
// Bad
const d = new Date();
const arr = getData();
const temp = process(data);
const user1 = getUser();
const item2 = getItem();

// Good
const currentTimestamp = new Date();
const userAccounts = getData();
const processedCustomerData = process(data);
const primaryUser = getUser();
const secondaryItem = getItem();
typescript
// Bad
const d = new Date();
const arr = getData();
const temp = process(data);
const user1 = getUser();
const item2 = getItem();

// Good
const currentTimestamp = new Date();
const userAccounts = getData();
const processedCustomerData = process(data);
const primaryUser = getUser();
const secondaryItem = getItem();

Functions

函数

typescript
// Bad
function get() { }
function process() { }
function handle() { }

// Good
function getUserById(userId: string) { }
function processPaymentTransaction(transaction: Transaction) { }
function handleFormSubmission(formData: FormData) { }
typescript
// Bad
function get() { }
function process() { }
function handle() { }

// Good
function getUserById(userId: string) { }
function processPaymentTransaction(transaction: Transaction) { }
function handleFormSubmission(formData: FormData) { }

Constants

常量

typescript
// Bad
const max = 100;
const url = 'https://...';

// Good
const MAXIMUM_UPLOAD_SIZE_BYTES = 100;
const PAYMENT_GATEWAY_API_URL = process.env.PAYMENT_GATEWAY_API_URL;
typescript
// Bad
const max = 100;
const url = 'https://...';

// Good
const MAXIMUM_UPLOAD_SIZE_BYTES = 100;
const PAYMENT_GATEWAY_API_URL = process.env.PAYMENT_GATEWAY_API_URL;

Types/Interfaces

类型/接口

typescript
// Bad
interface Props { }
type Data = { };

// Good
interface UserProfileComponentProps { }
type CustomerOrderData = { };
typescript
// Bad
interface Props { }
type Data = { };

// Good
interface UserProfileComponentProps { }
type CustomerOrderData = { };

Red Flags - Stop Immediately If You See

危险信号——一旦出现立即停止

  • Single letter variable names (except in tiny map/filter callbacks)
  • Numbers in variable names (
    user1
    ,
    data2
    ,
    temp3
    )
  • Abbreviations that aren't universal
  • TODO comments for core functionality
  • Placeholder implementations
  • Commented out code "for reference"
  • Functions that support "old and new" parameters
  • Any form of
    eslint-disable
  • Any form of
    @ts-ignore
  • Any form of
    biome-ignore
  • Any lint suppression comments
  • TypeScript errors or warnings
  • Biome check failures
  • Unused variables or imports
  • Missing type annotations
  • Using
    any
    type
  • Hardcoded strings or numbers (magic values)
  • Generic names like
    data
    ,
    value
    ,
    item
    ,
    temp
  • 单字母变量名(map/filter回调这类极小作用域除外)
  • 变量名中包含数字(
    user1
    data2
    temp3
    等)
  • 非通用缩写
  • 核心功能使用TODO注释
  • 占位符实现
  • 保留“供参考”的注释代码
  • 同时支持“旧版和新版”参数的函数
  • 任何形式的
    eslint-disable
  • 任何形式的
    @ts-ignore
  • 任何形式的
    biome-ignore
  • 任何类型的代码检查抑制注释
  • TypeScript错误或警告
  • Biome检查失败
  • 未使用的变量或导入
  • 缺失类型注解
  • 使用
    any
    类型
  • 硬编码字符串或数字(魔数)
  • 通用命名如
    data
    value
    item
    temp

Common Rationalizations

常见借口与实际情况

ExcuseReality
"Long names are verbose"Descriptive names prevent bugs
"We'll implement this later"Write complete code now or don't write it
"Need backward compatibility"Clean breaks are better than tech debt
"Just this one lint suppression"Fix the code, don't suppress the warning
"Everyone knows what this magic number means"They don't - use a named constant
"It's just a temporary variable"Temporary doesn't mean unclear
"I'll run the checks later"Run checks before committing, always
"TypeScript is too strict"Strict types prevent runtime errors
借口实际情况
“长命名过于冗长”描述性命名可预防bug
“我们之后再实现”现在就编写完整代码,否则不要开始
“需要向后兼容”彻底重构优于技术债务累积
“就这一次代码检查抑制”修复代码,而非抑制警告
“大家都知道这个魔数的含义”实际上没人知道——使用命名常量
“这只是个临时变量”临时变量也需要清晰命名
“我之后再运行检查”必须在提交前运行检查,无一例外
“TypeScript过于严格”严格类型可预防运行时错误

Checklist for Every Code Change

每次代码变更检查清单

Before committing any code, verify:
  • All variables have descriptive, verbose names
  • No single-letter variables (except tiny scopes)
  • No numbers in variable names (
    user1
    ,
    data2
    , etc.)
  • All functions are fully implemented (no placeholders)
  • No TODO comments for core functionality
  • No backward compatibility shims
  • No deprecated functions kept around
  • No
    eslint-disable
    ,
    @ts-ignore
    , or
    biome-ignore
  • No lint suppressions of any kind
  • No hardcoded values - all extracted to named constants
  • TypeScript check passes (
    tsc --noEmit
    or
    npm run typecheck
    )
  • Biome check passes (
    npx biome check .
    or
    npm run biome:check
    )
  • No unused variables or imports
  • All types are explicit (no
    any
    )
  • Code passes all linting without suppressions
提交任何代码前,请确认:
  • 所有变量均具备描述性、清晰的长命名
  • 无单字母变量(极小作用域除外)
  • 变量名中无数字(如
    user1
    data2
    等)
  • 所有函数均已完整实现(无占位符)
  • 核心功能无TODO注释
  • 无向后兼容垫片
  • 未保留已废弃函数
  • eslint-disable
    @ts-ignore
    biome-ignore
  • 无任何形式的代码检查抑制
  • 无硬编码值——所有值均提取为命名常量
  • TypeScript检查通过(
    tsc --noEmit
    npm run typecheck
  • Biome检查通过(
    npx biome check .
    npm run biome:check
  • 无未使用的变量或导入
  • 所有类型均为显式类型(无
    any
  • 代码无需抑制即可通过所有代码检查

Examples

示例

Before (Wrong)

优化前(错误示例)

typescript
function getData(id: string) {
  // TODO: Add validation
  const url = 'https://api.example.com/users';
  // @ts-ignore
  const res = fetch(`${url}/${id}`);
  return res;
}

const val = getData('123');
const x = val.map(i => i.name);
typescript
function getData(id: string) {
  // TODO: Add validation
  const url = 'https://api.example.com/users';
  // @ts-ignore
  const res = fetch(`${url}/${id}`);
  return res;
}

const val = getData('123');
const x = val.map(i => i.name);

After (Right)

优化后(正确示例)

typescript
const USER_API_BASE_URL = process.env.USER_API_BASE_URL;

interface UserApiResponse {
  userId: string;
  userName: string;
  userEmail: string;
}

async function fetchUserById(userId: string): Promise<UserApiResponse> {
  if (!userId || userId.trim().length === 0) {
    throw new Error('User ID is required and cannot be empty');
  }

  const response = await fetch(`${USER_API_BASE_URL}/users/${userId}`);

  if (!response.ok) {
    throw new Error(`Failed to fetch user: ${response.statusText}`);
  }

  const userData = await response.json();
  return userData;
}

const userResponse = await fetchUserById('123');
const userNames = userResponse.map(user => user.userName);
typescript
const USER_API_BASE_URL = process.env.USER_API_BASE_URL;

interface UserApiResponse {
  userId: string;
  userName: string;
  userEmail: string;
}

async function fetchUserById(userId: string): Promise<UserApiResponse> {
  if (!userId || userId.trim().length === 0) {
    throw new Error('User ID is required and cannot be empty');
  }

  const response = await fetch(`${USER_API_BASE_URL}/users/${userId}`);

  if (!response.ok) {
    throw new Error(`Failed to fetch user: ${response.statusText}`);
  }

  const userData = await response.json();
  return userData;
}

const userResponse = await fetchUserById('123');
const userNames = userResponse.map(user => user.userName);

Enforcement

执行要求

This skill is MANDATORY for all code changes.
If you find yourself:
  • Using vague variable names → Stop and rename
  • Writing TODO comments → Stop and implement
  • Adding backward compatibility → Stop and make a clean break
  • Adding lint suppressions → Stop and fix the code
  • Using magic values → Stop and extract to constants
  • Skipping type checks → Stop and run
    tsc --noEmit
  • Skipping Biome checks → Stop and run
    npx biome check .
  • Committing with type errors → Stop and fix the types
There are no exceptions.
此规范为所有代码变更的强制性要求。
如果你发现自己:
  • 使用模糊变量名 → 立即停止并重命名
  • 编写TODO注释 → 立即停止并实现功能
  • 添加向后兼容代码 → 立即停止并彻底重构
  • 添加代码检查抑制 → 立即停止并修复代码
  • 使用魔数 → 立即停止并提取为命名常量
  • 跳过类型检查 → 立即停止并运行
    tsc --noEmit
  • 跳过Biome检查 → 立即停止并运行
    npx biome check .
  • 提交存在类型错误的代码 → 立即停止并修复类型
无例外情况。

Quick Decision Tree

快速决策树

  1. Writing a variable? → Use a descriptive, verbose name
  2. Writing a function? → Implement it completely, no placeholders
  3. Changing an API? → Make a clean break, no backward compatibility
  4. Linter complaining? → Fix the code, never suppress
  5. Using a value? → Extract to a named constant
  6. Before committing? → Run
    tsc --noEmit
    and
    npx biome check .
  1. 编写变量? → 使用描述性、清晰的长命名
  2. 编写函数? → 完整实现功能,无占位符
  3. 修改API? → 彻底重构,无需考虑向后兼容
  4. 代码检查工具报错? → 修复代码,绝不抑制
  5. 使用固定值? → 提取为命名常量
  6. 提交前? → 运行
    tsc --noEmit
    npx biome check .

Final Rule

最终规则

Every line of code must be:
1. Clearly named with verbose, descriptive identifiers
2. Fully implemented with no placeholders
3. Breaking changes are fine - no backward compatibility
4. Passing all linters without suppressions
5. Free of hardcoded values
6. Pass TypeScript type checks
7. Pass Biome checks (lint + format)
Write code that reads like documentation.
每一行代码必须满足:
1. 使用清晰、具备描述性的标识符命名
2. 完整实现功能,无占位符
3. 允许破坏性变更——无需考虑向后兼容
4. 无需抑制即可通过所有代码检查
5. 无硬编码值
6. 通过TypeScript类型检查
7. 通过Biome检查(代码检查+格式化)
编写如同文档般易读的代码。

Pre-Commit Verification

提交前验证

ALWAYS run these commands before committing:
bash
undefined
提交前必须始终运行以下命令:
bash
undefined

1. TypeScript type check

1. TypeScript type check

npm run typecheck
npm run typecheck

or

or

tsc --noEmit
tsc --noEmit

2. Biome check (lint + format)

2. Biome check (lint + format)

npx biome check .
npx biome check .

or

or

npm run biome:check
npm run biome:check

3. If any errors, FIX them - never suppress or skip

3. 如果存在任何错误,立即修复——绝不抑制或跳过


**Only commit when all checks pass.**

**仅当所有检查通过时方可提交。**