style-guide-adherence
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseStyle 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:
- Project-specific style guide (if exists)
- Google style guide (if available for language)
- Language community best practices
遵循已确立的风格指南。一致性优先于个人偏好。
核心原则: 代码阅读的次数远多于编写的次数。一致的风格有助于阅读。
优先级顺序:
- 项目特定的风格指南(如果存在)
- Google风格指南(如果该语言有可用的指南)
- 语言社区的最佳实践
Google Style Guides
Google风格指南
Available Guides
可用指南
Key Principles (All Languages)
通用核心原则
| Principle | Description |
|---|---|
| Consistency | Match surrounding code style |
| Clarity | Prefer readable over clever |
| Simplicity | Simplest solution that works |
| Documentation | Document 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.tstypescript
// 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.tsFormatting
格式化
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
undefinedpython
undefinedClasses: 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
passclass Service:
def init(self):
self._cache = {} # internal use
def __private_method(self): # name mangling
passFiles: snake_case
Files: snake_case
user_service.py
user_service.py
undefinedundefinedFormatting
格式化
python
undefinedpython
undefinedIndent: 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
undefinedimport os
import sys
import requests
from flask import Flask
from myapp.utils import helper
undefinedDocstrings
文档字符串
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.gogo
// 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.goFormatting
格式化
Use - no options, no debate.
gofmtbash
undefined使用——无需额外选项,无需争论。
gofmtbash
undefinedFormat all files
Format all files
gofmt -w .
gofmt -w .
Or use goimports for imports too
Or use goimports for imports too
goimports -w .
undefinedgoimports -w .
undefinedEnforcing Style
风格强制执行
Automated Tools
自动化工具
| Language | Formatter | Linter |
|---|---|---|
| TypeScript | Prettier | ESLint |
| Python | Black | Pylint, Ruff |
| Go | gofmt | golangci-lint |
| Rust | rustfmt | clippy |
| 语言 | 格式化工具 | 代码检查工具 |
|---|---|---|
| TypeScript | Prettier | ESLint |
| Python | Black | Pylint, Ruff |
| Go | gofmt | golangci-lint |
| Rust | rustfmt | clippy |
Configuration Files
配置文件
Ensure these exist in the project:
TypeScript/JavaScript:
- or
.eslintrc.jseslint.config.js .prettierrc
Python:
- (Black, isort, mypy)
pyproject.toml - or
.pylintrcruff.toml
Go:
.golangci.yml
确保项目中存在以下配置文件:
TypeScript/JavaScript:
- 或
.eslintrc.jseslint.config.js .prettierrc
Python:
- (用于Black、isort、mypy)
pyproject.toml - 或
.pylintrcruff.toml
Go:
.golangci.yml
Pre-commit Hooks
提交前钩子
yaml
undefinedyaml
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
undefinedrepos:
- repo: local
hooks:
- id: format name: Format code entry: pnpm format language: system
- id: lint name: Lint code entry: pnpm lint language: system
undefinedWhen Project Style Differs
当项目风格与指南不同时
If project has established style that differs from Google:
- Follow project style - Consistency within project wins
- Document the difference - Note in CONTRIBUTING.md
- Don't mix styles - All code should match
markdown
<!-- CONTRIBUTING.md -->如果项目已确立的风格与Google指南不同:
- 遵循项目风格——项目内部的一致性优先
- 记录差异——在CONTRIBUTING.md中注明
- 不要混合风格——所有代码应保持一致
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字符
- [其他差异]
undefinedChecking Style
风格检查
Before committing:
bash
undefined提交前执行:
bash
undefinedRun 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
undefinedpnpm lint:fix
undefinedChecklist
检查清单
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
常见错误
| Mistake | Correction |
|---|---|
| Inconsistent naming | Follow project conventions |
| Long lines | Break at logical points |
| Mixed quote styles | Use project standard |
| Unorganized imports | Use import sorter |
| Manual formatting | Use automated formatter |
| 错误 | 修正方案 |
|---|---|
| 命名不一致 | 遵循项目约定 |
| 行过长 | 在逻辑断点处拆分 |
| 引号风格混合 | 使用项目标准 |
| 导入未整理 | 使用导入排序工具 |
| 手动格式化 | 使用自动化格式化工具 |
Integration
集成
This skill is applied by:
- - Step 7
issue-driven-development - - Style criterion
comprehensive-review
This skill ensures:
- Readable code
- Easy reviews
- Reduced cognitive load
- Team consistency
本技能适用于:
- ——第7步
issue-driven-development - ——风格评审标准
comprehensive-review
本技能可确保:
- 代码可读性
- 更易评审
- 降低认知负担
- 团队一致性