style-guide-adherence

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Style Guide Adherence

风格指南遵循

Overview

概述

Follow established style guides. Consistency over personal preference.
Core principle: Code is read more than written. Consistent style aids reading.
Priority order:
  1. Project-specific style guide (if exists)
  2. Google style guide (if available for language)
  3. Language community best practices
遵循已确立的风格指南。一致性优先于个人偏好。
核心原则: 代码阅读的次数远多于编写的次数。一致的风格有助于阅读。
优先级顺序:
  1. 项目特定的风格指南(如果存在)
  2. Google风格指南(如果该语言有可用的指南)
  3. 语言社区的最佳实践

Google Style Guides

Google风格指南

Available Guides

可用指南

Key Principles (All Languages)

通用核心原则

PrincipleDescription
ConsistencyMatch surrounding code style
ClarityPrefer readable over clever
SimplicitySimplest solution that works
DocumentationDocument the why, not the what
原则说明
一致性与周边代码的风格保持一致
清晰性优先选择可读性而非技巧性
简洁性采用可行的最简方案
文档化记录“为什么”而非“是什么”

TypeScript/JavaScript Style

TypeScript/JavaScript 风格

Naming

命名

typescript
// Classes: PascalCase
class UserService { }

// Interfaces: PascalCase (no I prefix)
interface User { }  // NOT IUser

// Functions/methods: camelCase
function fetchUserData() { }

// Variables/parameters: camelCase
const userName = 'Alice';

// Constants: UPPER_SNAKE_CASE
const MAX_RETRIES = 3;

// Private members: no underscore prefix
class Service {
  private cache: Map<string, Data>;  // NOT _cache
}

// Files: kebab-case
// user-service.ts, not userService.ts or UserService.ts
typescript
// Classes: PascalCase
class UserService { }

// Interfaces: PascalCase (no I prefix)
interface User { }  // NOT IUser

// Functions/methods: camelCase
function fetchUserData() { }

// Variables/parameters: camelCase
const userName = 'Alice';

// Constants: UPPER_SNAKE_CASE
const MAX_RETRIES = 3;

// Private members: no underscore prefix
class Service {
  private cache: Map<string, Data>;  // NOT _cache
}

// Files: kebab-case
// user-service.ts, not userService.ts or UserService.ts

Formatting

格式化

typescript
// Indent: 2 spaces
// Line length: 80 characters (100 max)
// Semicolons: required
// Quotes: single for strings
// Trailing commas: yes in multiline

const config = {
  name: 'app',
  version: '1.0.0',
  features: [
    'auth',
    'logging',
  ],
};
typescript
// Indent: 2 spaces
// Line length: 80 characters (100 max)
// Semicolons: required
// Quotes: single for strings
// Trailing commas: yes in multiline

const config = {
  name: 'app',
  version: '1.0.0',
  features: [
    'auth',
    'logging',
  ],
};

Imports

导入

typescript
// Order: external, then internal, then relative
// Alphabetize within groups

import { something } from 'external-lib';
import { other } from 'another-external';

import { internal } from '@/lib/internal';

import { local } from './local';
import { nearby } from '../nearby';
typescript
// Order: external, then internal, then relative
// Alphabetize within groups

import { something } from 'external-lib';
import { other } from 'another-external';

import { internal } from '@/lib/internal';

import { local } from './local';
import { nearby } from '../nearby';

Python Style

Python 风格

Naming

命名

python
undefined
python
undefined

Classes: PascalCase

Classes: PascalCase

class UserService: pass
class UserService: pass

Functions/variables: snake_case

Functions/variables: snake_case

def fetch_user_data(): pass
user_name = 'Alice'
def fetch_user_data(): pass
user_name = 'Alice'

Constants: UPPER_SNAKE_CASE

Constants: UPPER_SNAKE_CASE

MAX_RETRIES = 3
MAX_RETRIES = 3

Private: single underscore prefix

Private: single underscore prefix

class Service: def init(self): self._cache = {} # internal use
def __private_method(self):  # name mangling
    pass
class Service: def init(self): self._cache = {} # internal use
def __private_method(self):  # name mangling
    pass

Files: snake_case

Files: snake_case

user_service.py

user_service.py

undefined
undefined

Formatting

格式化

python
undefined
python
undefined

Indent: 4 spaces

Indent: 4 spaces

Line length: 80 characters

Line length: 80 characters

Use Black formatter for consistency

Use Black formatter for consistency

Imports order (use isort):

Imports order (use isort):

1. Standard library

1. Standard library

2. Third-party

2. Third-party

3. Local

3. Local

import os import sys
import requests from flask import Flask
from myapp.utils import helper
undefined
import os import sys
import requests from flask import Flask
from myapp.utils import helper
undefined

Docstrings

文档字符串

python
def calculate_total(items: list[Item], tax_rate: float) -> float:
    """Calculate the total price including tax.

    Args:
        items: List of items to sum.
        tax_rate: Tax rate as decimal (e.g., 0.08 for 8%).

    Returns:
        Total price including tax.

    Raises:
        ValueError: If tax_rate is negative.
    """
    if tax_rate < 0:
        raise ValueError("Tax rate cannot be negative")

    subtotal = sum(item.price for item in items)
    return subtotal * (1 + tax_rate)
python
def calculate_total(items: list[Item], tax_rate: float) -> float:
    """Calculate the total price including tax.

    Args:
        items: List of items to sum.
        tax_rate: Tax rate as decimal (e.g., 0.08 for 8%).

    Returns:
        Total price including tax.

    Raises:
        ValueError: If tax_rate is negative.
    """
    if tax_rate < 0:
        raise ValueError("Tax rate cannot be negative")

    subtotal = sum(item.price for item in items)
    return subtotal * (1 + tax_rate)

Go Style

Go 风格

Naming

命名

go
// Exported: PascalCase
type UserService struct { }
func FetchUser() { }

// Unexported: camelCase
type internalCache struct { }
func fetchFromDB() { }

// Acronyms: consistent case
type HTTPClient struct { }  // or httpClient for unexported
var userID string          // NOT userId

// Files: snake_case
// user_service.go
go
// Exported: PascalCase
type UserService struct { }
func FetchUser() { }

// Unexported: camelCase
type internalCache struct { }
func fetchFromDB() { }

// Acronyms: consistent case
type HTTPClient struct { }  // or httpClient for unexported
var userID string          // NOT userId

// Files: snake_case
// user_service.go

Formatting

格式化

Use
gofmt
- no options, no debate.
bash
undefined
使用
gofmt
——无需额外选项,无需争论。
bash
undefined

Format all files

Format all files

gofmt -w .
gofmt -w .

Or use goimports for imports too

Or use goimports for imports too

goimports -w .
undefined
goimports -w .
undefined

Enforcing Style

风格强制执行

Automated Tools

自动化工具

LanguageFormatterLinter
TypeScriptPrettierESLint
PythonBlackPylint, Ruff
Gogofmtgolangci-lint
Rustrustfmtclippy
语言格式化工具代码检查工具
TypeScriptPrettierESLint
PythonBlackPylint, Ruff
Gogofmtgolangci-lint
Rustrustfmtclippy

Configuration Files

配置文件

Ensure these exist in the project:
TypeScript/JavaScript:
  • .eslintrc.js
    or
    eslint.config.js
  • .prettierrc
Python:
  • pyproject.toml
    (Black, isort, mypy)
  • .pylintrc
    or
    ruff.toml
Go:
  • .golangci.yml
确保项目中存在以下配置文件:
TypeScript/JavaScript:
  • .eslintrc.js
    eslint.config.js
  • .prettierrc
Python:
  • pyproject.toml
    (用于Black、isort、mypy)
  • .pylintrc
    ruff.toml
Go:
  • .golangci.yml

Pre-commit Hooks

提交前钩子

yaml
undefined
yaml
undefined

.pre-commit-config.yaml

.pre-commit-config.yaml

repos:
  • repo: local hooks:
    • id: format name: Format code entry: pnpm format language: system
    • id: lint name: Lint code entry: pnpm lint language: system
undefined
repos:
  • repo: local hooks:
    • id: format name: Format code entry: pnpm format language: system
    • id: lint name: Lint code entry: pnpm lint language: system
undefined

When Project Style Differs

当项目风格与指南不同时

If project has established style that differs from Google:
  1. Follow project style - Consistency within project wins
  2. Document the difference - Note in CONTRIBUTING.md
  3. Don't mix styles - All code should match
markdown
<!-- CONTRIBUTING.md -->
如果项目已确立的风格与Google指南不同:
  1. 遵循项目风格——项目内部的一致性优先
  2. 记录差异——在CONTRIBUTING.md中注明
  3. 不要混合风格——所有代码应保持一致
markdown
<!-- CONTRIBUTING.md -->

Code Style

代码风格

This project uses [specific style] which differs from Google style:
  • We use tabs instead of spaces
  • Line length is 120 characters
  • [Other differences]
undefined
本项目使用[特定风格],与Google风格存在以下差异:
  • 我们使用制表符而非空格
  • 行长度为120字符
  • [其他差异]
undefined

Checking Style

风格检查

Before committing:
bash
undefined
提交前执行:
bash
undefined

Run formatter

Run formatter

pnpm format # or black, gofmt, etc.
pnpm format # 或 black、gofmt等

Run linter

Run linter

pnpm lint # or pylint, golangci-lint, etc.
pnpm lint # 或 pylint、golangci-lint等

Fix auto-fixable issues

Fix auto-fixable issues

pnpm lint:fix
undefined
pnpm lint:fix
undefined

Checklist

检查清单

Before committing:
  • Code formatted with project formatter
  • No linting errors
  • Naming follows conventions
  • Imports organized
  • Line length within limits
  • Consistent with surrounding code
提交前确认:
  • 代码已使用项目格式化工具格式化
  • 无代码检查错误
  • 命名遵循约定
  • 导入已整理
  • 行长度符合限制
  • 与周边代码风格一致

Common Mistakes

常见错误

MistakeCorrection
Inconsistent namingFollow project conventions
Long linesBreak at logical points
Mixed quote stylesUse project standard
Unorganized importsUse import sorter
Manual formattingUse automated formatter
错误修正方案
命名不一致遵循项目约定
行过长在逻辑断点处拆分
引号风格混合使用项目标准
导入未整理使用导入排序工具
手动格式化使用自动化格式化工具

Integration

集成

This skill is applied by:
  • issue-driven-development
    - Step 7
  • comprehensive-review
    - Style criterion
This skill ensures:
  • Readable code
  • Easy reviews
  • Reduced cognitive load
  • Team consistency
本技能适用于:
  • issue-driven-development
    ——第7步
  • comprehensive-review
    ——风格评审标准
本技能可确保:
  • 代码可读性
  • 更易评审
  • 降低认知负担
  • 团队一致性