Loading...
Loading...
Compare original and translation side by side
// ❌ Cryptic names
const d = new Date();
const u = getU();
const arr = data.filter(x => x.s === 'a');
// ✅ Descriptive names
const currentDate = new Date();
const currentUser = getCurrentUser();
const activeUsers = users.filter(user => user.status === 'active');
// ❌ Hungarian notation (outdated)
const strName = 'John';
const arrItems = [];
const bIsActive = true;
// ✅ Let the type system handle types
const name = 'John';
const items: Item[] = [];
const isActive = true;// ❌ 晦涩的命名
const d = new Date();
const u = getU();
const arr = data.filter(x => x.s === 'a');
// ✅ 描述性命名
const currentDate = new Date();
const currentUser = getCurrentUser();
const activeUsers = users.filter(user => user.status === 'active');
// ❌ 匈牙利命名法(已过时)
const strName = 'John';
const arrItems = [];
const bIsActive = true;
// ✅ 让类型系统处理类型
const name = 'John';
const items: Item[] = [];
const isActive = true;// ❌ Does too much
function processUserData(userId: string) {
const user = db.findUser(userId);
const orders = db.findOrders(userId);
const total = orders.reduce((sum, o) => sum + o.amount, 0);
sendEmail(user.email, `Your total: ${total}`);
updateAnalytics(userId, total);
return { user, orders, total };
}
// ✅ Single responsibility
function getUser(userId: string): User {
return db.findUser(userId);
}
function getUserOrders(userId: string): Order[] {
return db.findOrders(userId);
}
function calculateTotal(orders: Order[]): number {
return orders.reduce((sum, o) => sum + o.amount, 0);
}
function sendOrderSummary(user: User, total: number): void {
sendEmail(user.email, `Your total: ${total}`);
}
// ❌ Too many parameters
function createUser(name, email, age, role, department, manager, startDate) {}
// ✅ Use object parameter
interface CreateUserParams {
name: string;
email: string;
age?: number;
role: Role;
department: string;
managerId?: string;
startDate: Date;
}
function createUser(params: CreateUserParams): User {}// ❌ 职责过多
function processUserData(userId: string) {
const user = db.findUser(userId);
const orders = db.findOrders(userId);
const total = orders.reduce((sum, o) => sum + o.amount, 0);
sendEmail(user.email, `Your total: ${total}`);
updateAnalytics(userId, total);
return { user, orders, total };
}
// ✅ 单一职责
function getUser(userId: string): User {
return db.findUser(userId);
}
function getUserOrders(userId: string): Order[] {
return db.findOrders(userId);
}
function calculateTotal(orders: Order[]): number {
return orders.reduce((sum, o) => sum + o.amount, 0);
}
function sendOrderSummary(user: User, total: number): void {
sendEmail(user.email, `Your total: ${total}`);
}
// ❌ 参数过多
function createUser(name, email, age, role, department, manager, startDate) {}
// ✅ 使用对象参数
interface CreateUserParams {
name: string;
email: string;
age?: number;
role: Role;
department: string;
managerId?: string;
startDate: Date;
}
function createUser(params: CreateUserParams): User {}// ❌ Redundant comment
// Increment counter by 1
counter++;
// ❌ Outdated comment (code changed, comment didn't)
// Returns the user's full name
function getUserEmail(user: User) {
return user.email;
}
// ✅ Explains WHY, not WHAT
// Use binary search because the list is sorted and can have 100k+ items
const index = binarySearch(sortedItems, target);
// ✅ Warns about non-obvious behavior
// IMPORTANT: This function mutates the input array for performance reasons
function quickSort(arr: number[]): number[] {
// ...
}
// ✅ TODO with context
// TODO(john): Remove after migration completes - tracking in JIRA-1234
const legacyAdapter = new LegacyAdapter();// ❌ 冗余注释
// 将计数器加1
counter++;
// ❌ 过时注释(代码已修改,注释未更新)
// 返回用户的全名
function getUserEmail(user: User) {
return user.email;
}
// ✅ 解释原因,而非内容
// 由于列表已排序且可能包含10万+条数据,使用二分查找
const index = binarySearch(sortedItems, target);
// ✅ 提示非直观行为
// 重要:出于性能考虑,此函数会修改输入数组
function quickSort(arr: number[]): number[] {
// ...
}
// ✅ 带上下文的TODO
// TODO(john): 迁移完成后移除 - 跟踪于JIRA-1234
const legacyAdapter = new LegacyAdapter();// ❌ Multiple responsibilities
class UserManager {
createUser(data: UserData) { /* DB logic */ }
validateEmail(email: string) { /* Validation logic */ }
sendWelcomeEmail(user: User) { /* Email logic */ }
generateReport(users: User[]) { /* Report logic */ }
}
// ✅ Single responsibility each
class UserRepository {
create(data: UserData): User { /* DB logic */ }
findById(id: string): User | null { /* DB logic */ }
}
class UserValidator {
validateEmail(email: string): boolean { /* Validation */ }
validatePassword(password: string): ValidationResult { /* Validation */ }
}
class EmailService {
sendWelcomeEmail(user: User): void { /* Email logic */ }
}
class UserReportGenerator {
generate(users: User[]): Report { /* Report logic */ }
}// ❌ 多职责
class UserManager {
createUser(data: UserData) { /* 数据库逻辑 */ }
validateEmail(email: string) { /* 验证逻辑 */ }
sendWelcomeEmail(user: User) { /* 邮件逻辑 */ }
generateReport(users: User[]) { /* 报表逻辑 */ }
}
// ✅ 单一职责
class UserRepository {
create(data: UserData): User { /* 数据库逻辑 */ }
findById(id: string): User | null { /* 数据库逻辑 */ }
}
class UserValidator {
validateEmail(email: string): boolean { /* 验证逻辑 */ }
validatePassword(password: string): ValidationResult { /* 验证逻辑 */ }
}
class EmailService {
sendWelcomeEmail(user: User): void { /* 邮件逻辑 */ }
}
class UserReportGenerator {
generate(users: User[]): Report { /* 报表逻辑 */ }
}// ❌ Must modify to add new payment methods
class PaymentProcessor {
process(payment: Payment) {
if (payment.type === 'credit') {
// Credit card logic
} else if (payment.type === 'paypal') {
// PayPal logic
} else if (payment.type === 'crypto') {
// Crypto logic - had to modify existing code!
}
}
}
// ✅ Open for extension, closed for modification
interface PaymentMethod {
process(amount: number): Promise<PaymentResult>;
}
class CreditCardPayment implements PaymentMethod {
async process(amount: number): Promise<PaymentResult> { /* ... */ }
}
class PayPalPayment implements PaymentMethod {
async process(amount: number): Promise<PaymentResult> { /* ... */ }
}
// New payment method - no modification to existing code
class CryptoPayment implements PaymentMethod {
async process(amount: number): Promise<PaymentResult> { /* ... */ }
}
class PaymentProcessor {
constructor(private method: PaymentMethod) {}
async process(amount: number): Promise<PaymentResult> {
return this.method.process(amount);
}
}// ❌ 添加新支付方式时必须修改现有代码
class PaymentProcessor {
process(payment: Payment) {
if (payment.type === 'credit') {
// 信用卡逻辑
} else if (payment.type === 'paypal') {
// PayPal逻辑
} else if (payment.type === 'crypto') {
// 加密货币逻辑 - 不得不修改现有代码!
}
}
}
// ✅ 对扩展开放,对修改关闭
interface PaymentMethod {
process(amount: number): Promise<PaymentResult>;
}
class CreditCardPayment implements PaymentMethod {
async process(amount: number): Promise<PaymentResult> { /* ... */ }
}
class PayPalPayment implements PaymentMethod {
async process(amount: number): Promise<PaymentResult> { /* ... */ }
}
// 新增支付方式 - 无需修改现有代码
class CryptoPayment implements PaymentMethod {
async process(amount: number): Promise<PaymentResult> { /* ... */ }
}
class PaymentProcessor {
constructor(private method: PaymentMethod) {}
async process(amount: number): Promise<PaymentResult> {
return this.method.process(amount);
}
}// ❌ Violates LSP - Square breaks Rectangle contract
class Rectangle {
constructor(public width: number, public height: number) {}
setWidth(w: number) { this.width = w; }
setHeight(h: number) { this.height = h; }
getArea() { return this.width * this.height; }
}
class Square extends Rectangle {
setWidth(w: number) {
this.width = w;
this.height = w; // Unexpected side effect!
}
setHeight(h: number) {
this.width = h;
this.height = h; // Unexpected side effect!
}
}
// ✅ Proper abstraction
interface Shape {
getArea(): number;
}
class Rectangle implements Shape {
constructor(private width: number, private height: number) {}
getArea() { return this.width * this.height; }
}
class Square implements Shape {
constructor(private side: number) {}
getArea() { return this.side * this.side; }
}// ❌ 违反LSP - Square破坏了Rectangle的契约
class Rectangle {
constructor(public width: number, public height: number) {}
setWidth(w: number) { this.width = w; }
setHeight(h: number) { this.height = h; }
getArea() { return this.width * this.height; }
}
class Square extends Rectangle {
setWidth(w: number) {
this.width = w;
this.height = w; // 意外的副作用!
}
setHeight(h: number) {
this.width = h;
this.height = h; // 意外的副作用!
}
}
// ✅ 正确的抽象
interface Shape {
getArea(): number;
}
class Rectangle implements Shape {
constructor(private width: number, private height: number) {}
getArea() { return this.width * this.height; }
}
class Square implements Shape {
constructor(private side: number) {}
getArea() { return this.side * this.side; }
}// ❌ Fat interface
interface Worker {
work(): void;
eat(): void;
sleep(): void;
attendMeeting(): void;
writeReport(): void;
}
// Robot can't eat or sleep!
class Robot implements Worker {
work() { /* ... */ }
eat() { throw new Error('Robots do not eat'); } // Forced to implement
sleep() { throw new Error('Robots do not sleep'); }
// ...
}
// ✅ Segregated interfaces
interface Workable {
work(): void;
}
interface Eatable {
eat(): void;
}
interface Sleepable {
sleep(): void;
}
class Human implements Workable, Eatable, Sleepable {
work() { /* ... */ }
eat() { /* ... */ }
sleep() { /* ... */ }
}
class Robot implements Workable {
work() { /* ... */ }
}// ❌ 臃肿接口
interface Worker {
work(): void;
eat(): void;
sleep(): void;
attendMeeting(): void;
writeReport(): void;
}
// 机器人不能吃饭或睡觉!
class Robot implements Worker {
work() { /* ... */ }
eat() { throw new Error('Robots do not eat'); } // 被迫实现
sleep() { throw new Error('Robots do not sleep'); }
// ...
}
// ✅ 拆分后的接口
interface Workable {
work(): void;
}
interface Eatable {
eat(): void;
}
interface Sleepable {
sleep(): void;
}
class Human implements Workable, Eatable, Sleepable {
work() { /* ... */ }
eat() { /* ... */ }
sleep() { /* ... */ }
}
class Robot implements Workable {
work() { /* ... */ }
}// ❌ High-level depends on low-level
class OrderService {
private db = new MySQLDatabase(); // Concrete dependency
private mailer = new SendGridMailer(); // Concrete dependency
createOrder(data: OrderData) {
const order = this.db.insert('orders', data);
this.mailer.send(data.email, 'Order confirmed');
return order;
}
}
// ✅ Depend on abstractions
interface Database {
insert(table: string, data: unknown): unknown;
find(table: string, query: unknown): unknown[];
}
interface Mailer {
send(to: string, message: string): void;
}
class OrderService {
constructor(
private db: Database,
private mailer: Mailer
) {}
createOrder(data: OrderData) {
const order = this.db.insert('orders', data);
this.mailer.send(data.email, 'Order confirmed');
return order;
}
}
// Now we can inject any implementation
const service = new OrderService(
new PostgresDatabase(),
new SESMailer()
);// ❌ 高层模块依赖低层模块
class OrderService {
private db = new MySQLDatabase(); // 具体依赖
private mailer = new SendGridMailer(); // 具体依赖
createOrder(data: OrderData) {
const order = this.db.insert('orders', data);
this.mailer.send(data.email, 'Order confirmed');
return order;
}
}
// ✅ 依赖抽象
interface Database {
insert(table: string, data: unknown): unknown;
find(table: string, query: unknown): unknown[];
}
interface Mailer {
send(to: string, message: string): void;
}
class OrderService {
constructor(
private db: Database,
private mailer: Mailer
) {}
createOrder(data: OrderData) {
const order = this.db.insert('orders', data);
this.mailer.send(data.email, 'Order confirmed');
return order;
}
}
// 现在我们可以注入任何实现
const service = new OrderService(
new PostgresDatabase(),
new SESMailer()
);undefinedundefinedundefinedundefinedundefinedundefinedfilter()const active = items.filter(i => i.active)filter()const active = items.filter(i => i.active)
---
---// High complexity (10+) - hard to test and maintain
function processOrder(order: Order): Result {
if (order.status === 'pending') { // +1
if (order.paymentMethod === 'card') { // +1
if (order.amount > 1000) { // +1
// ...
} else if (order.amount > 100) { // +1
// ...
} else {
// ...
}
} else if (order.paymentMethod === 'cash') { // +1
// ...
}
} else if (order.status === 'processing') { // +1
// ...
}
// ... more branches
}
// Lower complexity - extract conditions
function processOrder(order: Order): Result {
const processor = getProcessor(order.paymentMethod);
const tier = getPricingTier(order.amount);
return processor.process(order, tier);
}// 高复杂度(10+)- 难以测试和维护
function processOrder(order: Order): Result {
if (order.status === 'pending') { // +1
if (order.paymentMethod === 'card') { // +1
if (order.amount > 1000) { // +1
// ...
} else if (order.amount > 100) { // +1
// ...
} else {
// ...
}
} else if (order.paymentMethod === 'cash') { // +1
// ...
}
} else if (order.status === 'processing') { // +1
// ...
}
// ... 更多分支
}
// 低复杂度 - 提取条件
function processOrder(order: Order): Result {
const processor = getProcessor(order.paymentMethod);
const tier = getPricingTier(order.amount);
return processor.process(order, tier);
}| Metric | Target | Why |
|---|---|---|
| Cyclomatic Complexity | < 10 per function | Testability |
| Function Length | < 50 lines | Readability |
| File Length | < 400 lines | Maintainability |
| Test Coverage | > 80% | Confidence |
| Duplication | < 3% | DRY principle |
| 指标 | 目标值 | 原因 |
|---|---|---|
| 圈复杂度 | 每个函数<10 | 可测试性 |
| 函数长度 | <50行 | 可读性 |
| 文件长度 | <400行 | 可维护性 |
| 测试覆盖率 | >80% | 可信度 |
| 代码重复率 | <3% | DRY原则 |
// .eslintrc.js
module.exports = {
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
],
rules: {
// Prevent bugs
'no-unused-vars': 'error',
'@typescript-eslint/no-floating-promises': 'error',
'@typescript-eslint/no-misused-promises': 'error',
// Code quality
'complexity': ['warn', 10],
'max-lines-per-function': ['warn', 50],
'max-depth': ['warn', 3],
// Consistency
'prefer-const': 'error',
'no-var': 'error',
}
};// .eslintrc.js
module.exports = {
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
],
rules: {
// 预防bug
'no-unused-vars': 'error',
'@typescript-eslint/no-floating-promises': 'error',
'@typescript-eslint/no-misused-promises': 'error',
// 代码质量
'complexity': ['warn', 10],
'max-lines-per-function': ['warn', 50],
'max-depth': ['warn', 3],
// 一致性
'prefer-const': 'error',
'no-var': 'error',
}
};// package.json
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{ts,tsx}": [
"eslint --fix",
"prettier --write"
],
"*.{json,md}": [
"prettier --write"
]
}
}// package.json
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{ts,tsx}": [
"eslint --fix",
"prettier --write"
],
"*.{json,md}": [
"prettier --write"
]
}
}這些是程式碼品質中最常見且代價最高的錯誤
这些是代码质量中最常见且代价最高的错误
Factory.*Factory|Abstract.*Abstract|interface.*\{.*\}(?=.*interface.*\{.*\})|Strategy.*StrategyFactory.*Factory|Abstract.*Abstract|interface.*\{.*\}(?=.*interface.*\{.*\})|Strategy.*Strategyusercustomerclientaccount(user|customer|client|account).*=.*find|(get|fetch|retrieve|load).*Userusercustomerclientaccount(user|customer|client|account).*=.*find|(get|fetch|retrieve|load).*User}{\{.*\{.*\{.*\{|if.*if.*if.*if|\.then\(.*\.then\(.*\.then\(}{\{.*\{.*\{.*\{|if.*if.*if.*if|\.then\(.*\.then\(.*\.then\(86400\b(86400|3600|1000|60000|1024|65535)\b|status\s*===?\s*['"][^'"]+['"]86400\b(86400|3600|1000|60000|1024|65535)\b|status\s*===?\s*['"][^'"]+['"]import.*from.*\.\.\/\.\.\/\.\.\/|require\(.*\.\..*\.\..*\.\.\)|lines.*>\s*1000import.*from.*\.\.\/\.\.\/\.\.\/|require\(.*\.\..*\.\..*\.\.\)|lines.*>\s*1000console\.(log|debug|info)\(*.ts*.jsconsole\.(log|debug|info)\(*.ts*.jsTSAnyKeyword*.ts*.tsxTSAnyKeyword*.ts*.tsxfunction\s+\w+\s*\([^)]*,\s*[^)]*,\s*[^)]*,\s*[^)]*,\s*[^)]*\)|=>\s*\([^)]*,\s*[^)]*,\s*[^)]*,\s*[^)]*,\s*[^)]*\)function(options: Options)*.ts*.jsfunction\s+\w+\s*\([^)]*,\s*[^)]*,\s*[^)]*,\s*[^)]*,\s*[^)]*\)|=>\s*\([^)]*,\s*[^)]*,\s*[^)]*,\s*[^)]*,\s*[^)]*\)function(options: Options)*.ts*.js//\s*TODO(?!.*#\d|.*JIRA|.*\w+-\d+)// TODO(#123): description*.ts*.js*.tsx*.jsx//\s*TODO(?!.*#\d|.*JIRA|.*\w+-\d+)// TODO(#123): 描述*.ts*.js*.tsx*.jsximport.*from\s+['"]\.\.\/\.\.\/\.\.\/|require\s*\(\s*['"]\.\.\/\.\.\/\.\.\/import { X } from '@/modules/x'*.ts*.js*.tsx*.jsximport.*from\s+['"]\.\.\/\.\.\/\.\.\/|require\s*\(\s*['"]\.\.\/\.\.\/\.\.\/import { X } from '@/modules/x'*.ts*.js*.tsx*.jsx