code-smell-detector

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Code Smell Detector Skill

代码异味检测Skill

コードの問題パターン(コードスメル)を検出するスキルです。
这是一款检测代码问题模式(Code Smell)的Skill。

概要

概述

保守性を低下させるコードパターンを検出し、リファクタリングを提案します。
检测会降低代码可维护性的代码模式,并提供重构建议。

検出するコードスメル

检测的代码异味

1. Long Method(長すぎるメソッド)

1. Long Method(过长方法)

javascript
// ❌ Bad: 100行のメソッド
function processOrder(order) {
  // 検証ロジック 20行
  // 在庫チェック 15行
  // 価格計算 20行
  // 決済処理 25行
  // メール送信 15行
  // ログ記録 5行
}

// ✅ Good: 分割
function processOrder(order) {
  validateOrder(order);
  checkInventory(order);
  const total = calculateTotal(order);
  processPayment(order, total);
  sendConfirmationEmail(order);
  logOrder(order);
}
javascript
// ❌ 不良示例:100行的方法
function processOrder(order) {
  // 验证逻辑 20行
  // 库存检查 15行
  // 价格计算 20行
  // 支付处理 25行
  // 邮件发送 15行
  // 日志记录 5行
}

// ✅ 良好示例:拆分方法
function processOrder(order) {
  validateOrder(order);
  checkInventory(order);
  const total = calculateTotal(order);
  processPayment(order, total);
  sendConfirmationEmail(order);
  logOrder(order);
}

2. Duplicate Code(重複コード)

2. Duplicate Code(重复代码)

python
undefined
python
undefined

❌ Bad

❌ 不良示例

def calculate_user_discount(user): if user.type == 'premium': return user.total * 0.9 elif user.type == 'vip': return user.total * 0.8 return user.total
def calculate_order_price(order): if order.user.type == 'premium': return order.total * 0.9 elif order.user.type == 'vip': return order.total * 0.8 return order.total
def calculate_user_discount(user): if user.type == 'premium': return user.total * 0.9 elif user.type == 'vip': return user.total * 0.8 return user.total
def calculate_order_price(order): if order.user.type == 'premium': return order.total * 0.9 elif order.user.type == 'vip': return order.total * 0.8 return order.total

✅ Good

✅ 良好示例

DISCOUNT_RATES = { 'premium': 0.9, 'vip': 0.8, 'regular': 1.0 }
def apply_discount(total, user_type): rate = DISCOUNT_RATES.get(user_type, 1.0) return total * rate
undefined
DISCOUNT_RATES = { 'premium': 0.9, 'vip': 0.8, 'regular': 1.0 }
def apply_discount(total, user_type): rate = DISCOUNT_RATES.get(user_type, 1.0) return total * rate
undefined

3. Large Class(巨大クラス)

3. Large Class(巨大类)

java
// ❌ Bad: 1000行のクラス
class UserManager {
    void createUser() {}
    void updateUser() {}
    void deleteUser() {}
    void sendEmail() {}
    void generateReport() {}
    void processPayment() {}
    void managePermissions() {}
    // ... 50個のメソッド
}

// ✅ Good: 責務を分離
class UserRepository {
    void create(User user) {}
    void update(User user) {}
    void delete(String id) {}
}

class EmailService {
    void send(Email email) {}
}

class PaymentService {
    void process(Payment payment) {}
}
java
// ❌ 不良示例:1000行的类
class UserManager {
    void createUser() {}
    void updateUser() {}
    void deleteUser() {}
    void sendEmail() {}
    void generateReport() {}
    void processPayment() {}
    void managePermissions() {}
    // ... 50个方法
}

// ✅ 良好示例:职责分离
class UserRepository {
    void create(User user) {}
    void update(User user) {}
    void delete(String id) {}
}

class EmailService {
    void send(Email email) {}
}

class PaymentService {
    void process(Payment payment) {}
}

4. Magic Numbers(マジックナンバー)

4. Magic Numbers(魔法数值)

javascript
// ❌ Bad
if (user.age > 18 && user.score >= 75) {
  // ...
}

// ✅ Good
const ADULT_AGE = 18;
const PASSING_SCORE = 75;

if (user.age > ADULT_AGE && user.score >= PASSING_SCORE) {
  // ...
}
javascript
// ❌ 不良示例
if (user.age > 18 && user.score >= 75) {
  // ...
}

// ✅ 良好示例
const ADULT_AGE = 18;
const PASSING_SCORE = 75;

if (user.age > ADULT_AGE && user.score >= PASSING_SCORE) {
  // ...
}

5. Deep Nesting(深いネスト)

5. Deep Nesting(深层嵌套)

python
undefined
python
undefined

❌ Bad

❌ 不良示例

def process(data): if data: if data.valid: if data.user: if data.user.active: if data.amount > 0: # 処理 return True return False
def process(data): if data: if data.valid: if data.user: if data.user.active: if data.amount > 0: # 处理 return True return False

✅ Good: Early return

✅ 良好示例:提前返回

def process(data): if not data or not data.valid: return False
if not data.user or not data.user.active:
    return False

if data.amount <= 0:
    return False

# 処理
return True
undefined
def process(data): if not data or not data.valid: return False
if not data.user or not data.user.active:
    return False

if data.amount <= 0:
    return False

# 处理
return True
undefined

6. Dead Code(デッドコード)

6. Dead Code(死代码)

typescript
// ❌ Bad
function calculatePrice(item: Item): number {
  const tax = 0.1; // 使われていない
  const oldPrice = item.price * 1.2; // 使われていない

  return item.price;
}

// ✅ Good
function calculatePrice(item: Item): number {
  return item.price;
}
typescript
// ❌ 不良示例
function calculatePrice(item: Item): number {
  const tax = 0.1; // 未使用
  const oldPrice = item.price * 1.2; // 未使用

  return item.price;
}

// ✅ 良好示例
function calculatePrice(item: Item): number {
  return item.price;
}

7. Comment Smell(不適切なコメント)

7. Comment Smell(不恰当注释)

java
// ❌ Bad
// このメソッドはユーザーを取得します
public User getUser(String id) {
    // IDでデータベースを検索
    return database.find(id);
}

// ✅ Good: コードで表現
public User findUserById(String id) {
    return userRepository.findById(id);
}
java
// ❌ 不良示例
// 此方法用于获取用户
public User getUser(String id) {
    // 根据ID查询数据库
    return database.find(id);
}

// ✅ 良好示例:用代码表达意图
public User findUserById(String id) {
    return userRepository.findById(id);
}

8. Feature Envy(機能への羨望)

8. Feature Envy(特性依恋)

python
undefined
python
undefined

❌ Bad: OrderクラスがUserの詳細を知りすぎ

❌ 不良示例:Order类过度了解User的细节

class Order: def calculate_discount(self, user): if user.type == 'premium': return self.total * user.premium_rate elif user.type == 'vip': return self.total * user.vip_rate return self.total
class Order: def calculate_discount(self, user): if user.type == 'premium': return self.total * user.premium_rate elif user.type == 'vip': return self.total * user.vip_rate return self.total

✅ Good: Userに責務を移動

✅ 良好示例:将职责转移给User

class User: def get_discount_rate(self): rates = {'premium': 0.9, 'vip': 0.8} return rates.get(self.type, 1.0)
class Order: def calculate_discount(self, user): return self.total * user.get_discount_rate()
undefined
class User: def get_discount_rate(self): rates = {'premium': 0.9, 'vip': 0.8} return rates.get(self.type, 1.0)
class Order: def calculate_discount(self, user): return self.total * user.get_discount_rate()
undefined

9. Primitive Obsession(基本型への執着)

9. Primitive Obsession(基本类型过度使用)

typescript
// ❌ Bad
function sendEmail(to: string, subject: string, body: string) {
  // ...
}

sendEmail('user@example.com', 'Hello', 'Message');

// ✅ Good
class Email {
  constructor(
    public to: string,
    public subject: string,
    public body: string
  ) {}

  validate(): boolean {
    return /\S+@\S+\.\S+/.test(this.to);
  }
}

function sendEmail(email: Email) {
  if (!email.validate()) {
    throw new Error('Invalid email');
  }
  // ...
}
typescript
// ❌ 不良示例
function sendEmail(to: string, subject: string, body: string) {
  // ...
}

sendEmail('user@example.com', 'Hello', 'Message');

// ✅ 良好示例
class Email {
  constructor(
    public to: string,
    public subject: string,
    public body: string
  ) {}

  validate(): boolean {
    return /\S+@\S+\.\S+/.test(this.to);
  }
}

function sendEmail(email: Email) {
  if (!email.validate()) {
    throw new Error('Invalid email');
  }
  // ...
}

10. Switch Statement Smell

10. Switch Statement Smell(Switch语句异味)

java
// ❌ Bad
public double calculateArea(Shape shape) {
    switch (shape.getType()) {
        case CIRCLE:
            return Math.PI * shape.getRadius() * shape.getRadius();
        case RECTANGLE:
            return shape.getWidth() * shape.getHeight();
        case TRIANGLE:
            return 0.5 * shape.getBase() * shape.getHeight();
    }
    return 0;
}

// ✅ Good: ポリモーフィズム
interface Shape {
    double calculateArea();
}

class Circle implements Shape {
    public double calculateArea() {
        return Math.PI * radius * radius;
    }
}

class Rectangle implements Shape {
    public double calculateArea() {
        return width * height;
    }
}
java
// ❌ 不良示例
public double calculateArea(Shape shape) {
    switch (shape.getType()) {
        case CIRCLE:
            return Math.PI * shape.getRadius() * shape.getRadius();
        case RECTANGLE:
            return shape.getWidth() * shape.getHeight();
        case TRIANGLE:
            return 0.5 * shape.getBase() * shape.getHeight();
    }
    return 0;
}

// ✅ 良好示例:多态
interface Shape {
    double calculateArea();
}

class Circle implements Shape {
    public double calculateArea() {
        return Math.PI * radius * radius;
    }
}

class Rectangle implements Shape {
    public double calculateArea() {
        return width * height;
    }
}

検出レポート例

检测报告示例

markdown
undefined
markdown
undefined

コードスメル検出レポート

代码异味检测报告

ファイル: user_service.py

文件: user_service.py

[HIGH] Long Method

[高优先级] Long Method

場所: Line 45-120 (76行) メソッド:
process_user_registration
推奨: 以下に分割
  • validate_user_data
  • create_user_account
  • send_welcome_email
  • initialize_user_settings
位置: 第45-120行(共76行) 方法:
process_user_registration
建议: 拆分为以下方法
  • validate_user_data
  • create_user_account
  • send_welcome_email
  • initialize_user_settings

[MEDIUM] Duplicate Code

[中优先级] Duplicate Code

場所: Line 150-165, Line 200-215 重複度: 95% 推奨: 共通関数
apply_user_discount
に抽出
位置: 第150-165行、第200-215行 重复度: 95% 建议: 提取为公共函数
apply_user_discount

[LOW] Magic Number

[低优先级] Magic Number

場所: Line 78 コード:
if age > 18
推奨:
ADULT_AGE = 18
と定数化
位置: 第78行 代码:
if age > 18
建议: 定义常量
ADULT_AGE = 18

統計

统计

  • Total Code Smells: 12
  • High Priority: 3
  • Medium Priority: 5
  • Low Priority: 4
undefined
  • 总代码异味数: 12
  • 高优先级: 3
  • 中优先级: 5
  • 低优先级: 4
undefined

バージョン情報

版本信息

  • スキルバージョン: 1.0.0
  • Skill版本: 1.0.0