Token导航 LogoToken导航TokenDH.com
前端设计权限需确认github未标认证来源可访问许可证需确认审计通过

code-refactoring-solid代码重构扎实

Agent Skill

code-refactoring-solid 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

196

周安装

8

GitHub Stars

1

下载量

63
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:code-refactoring-solid(代码重构扎实)
来源仓库:https://github.com/forever19735/garbage
仓库路径:skills/code-refactoring-solid
安装命令:
npx skills add https://github.com/forever19735/garbage --skill code-refactoring-solid
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/forever19735/garbage --skill code-refactoring-solid

简介

code-refactoring-solid 基于 SOLID 原则重构代码,解决多重职责、紧耦合与高内聚缺失等问题。

  • 适用于复杂类难以测试或修改的场景,通过接口隔离与依赖注入提升扩展性与可测性。
  • 提供具体反例与重构前后对比,指导如何拆分 DataManager 类并应用工厂模式解耦创建逻辑。
  • 使用前应确认有足够权限修改类结构与测试文件,并确保单元测试能捕获行为变更以防回归缺陷。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

🏗️ Code Refactoring with SOLID Principles

When to use this skill

Use this skill when:

  • Refactoring existing code to improve maintainability
  • Code has grown complex and difficult to modify
  • Adding new features requires changing multiple unrelated parts
  • Unit testing is difficult due to tight coupling
  • Code violates SOLID principles
  • Planning architectural improvements

How to use it

🎯 SOLID Principles Overview

S - Single Responsibility Principle (SRP)

Definition: A class should have only one reason to change.

Violations in current codebase:

# ❌ BAD: DataManager does too much
class DataManager:
    def load_data(self, data_type):
        # Loading logic
    def save_data(self, data_type, data):
        # Saving logic
    def delete_data(self, data_type):
        # Deletion logic
    # Also handles Firebase connection, validation, etc.

Refactored:

# ✅ GOOD: Separate responsibilities
class FirebaseConnection:
    """Handles Firebase connection only"""
    def connect(self): pass
    def is_available(self): pass

class DataRepository:
    """Handles data CRUD operations only"""
    def __init__(self, connection: FirebaseConnection):
        self.connection = connection

    def load(self, data_type): pass
    def save(self, data_type, data): pass
    def delete(self, data_type): pass

class DataValidator:
    """Handles data validation only"""
    def validate_group_ids(self, ids): pass
    def validate_schedule(self, schedule): pass

O - Open/Closed Principle (OCP)

Definition: Software entities should be open for extension but closed for modification.

Violations:

# ❌ BAD: Must modify function to add new command
def handle_message(event):
    if event.text.startswith("@time"):
        # handle time
    elif event.text.startswith("@day"):
        # handle day
    elif event.text.startswith("@week"):
        # handle week
    # Adding new command requires modifying this function

Refactored:

# ✅ GOOD: Command pattern - add new commands without modifying handler
class Command(ABC):
    @abstractmethod
    def can_handle(self, text: str) -> bool:
        pass

    @abstractmethod
    def execute(self, event) -> str:
        pass

class TimeCommand(Command):
    def can_handle(self, text: str) -> bool:
        return text.startswith("@time")

    def execute(self, event) -> str:
        # Handle time command
        pass

class CommandHandler:
    def __init__(self):
        self.commands: List[Command] = []

    def register(self, command: Command):
        self.commands.append(command)

    def handle(self, event):
        for command in self.commands:
            if command.can_handle(event.text):
                return command.execute(event)

L - Liskov Substitution Principle (LSP)

Definition: Objects of a superclass should be replaceable with objects of its subclasses.

Application:

# ✅ GOOD: Storage abstraction
class Storage(ABC):
    @abstractmethod
    def save(self, key: str, value: Any) -> bool:
        pass

    @abstractmethod
    def load(self, key: str) -> Any:
        pass

class FirebaseStorage(Storage):
    def save(self, key: str, value: Any) -> bool:
        # Firebase implementation
        pass

    def load(self, key: str) -> Any:
        # Firebase implementation
        pass

class LocalFileStorage(Storage):
    def save(self, key: str, value: Any) -> bool:
        # File implementation
        pass

    def load(self, key: str) -> Any:
        # File implementation
        pass

# Can swap implementations without changing client code
def save_schedule(storage: Storage, schedule):
    storage.save("schedule", schedule)

I - Interface Segregation Principle (ISP)

Definition: Clients should not be forced to depend on interfaces they don't use.

Violations:

# ❌ BAD: Fat interface
class BotService:
    def handle_message(self): pass
    def handle_join(self): pass
    def handle_leave(self): pass
    def send_broadcast(self): pass
    def schedule_task(self): pass
    def validate_input(self): pass
    # Too many responsibilities

Refactored:

# ✅ GOOD: Segregated interfaces
class MessageHandler(ABC):
    @abstractmethod
    def handle_message(self, event): pass

class GroupEventHandler(ABC):
    @abstractmethod
    def handle_join(self, event): pass
    @abstractmethod
    def handle_leave(self, event): pass

class BroadcastService(ABC):
    @abstractmethod
    def send_broadcast(self, group_id: str, message: str): pass

class ScheduleService(ABC):
    @abstractmethod
    def schedule_task(self, task): pass

D - Dependency Inversion Principle (DIP)

Definition: High-level modules should not depend on low-level modules. Both should depend on abstractions.

Violations:

# ❌ BAD: Direct dependency on concrete class
class ScheduleManager:
    def __init__(self):
        self.firebase = firebase_service.firebase_service_instance  # Tight coupling

    def save_schedule(self, schedule):
        self.firebase.save_group_schedules(schedule)

Refactored:

# ✅ GOOD: Depend on abstraction
class ScheduleRepository(ABC):
    @abstractmethod
    def save(self, schedule): pass
    @abstractmethod
    def load(self): pass

class ScheduleManager:
    def __init__(self, repository: ScheduleRepository):
        self.repository = repository  # Depends on abstraction

    def save_schedule(self, schedule):
        self.repository.save(schedule)

# Concrete implementation
class FirebaseScheduleRepository(ScheduleRepository):
    def __init__(self, firebase_service):
        self.firebase = firebase_service

    def save(self, schedule):
        return self.firebase.save_group_schedules(schedule)

    def load(self):
        return self.firebase.load_group_schedules()

🔧 Refactoring Patterns

1. Extract Class

When: A class is doing too much

# Before
class BotHandler:
    def parse_time(self, text): pass
    def parse_members(self, text): pass
    def validate_time(self, hour, minute): pass
    def validate_members(self, members): pass
    def format_message(self, action, details): pass
    def handle_command(self, event): pass

# After
class InputParser:
    def parse_time(self, text): pass
    def parse_members(self, text): pass

class InputValidator:
    def validate_time(self, hour, minute): pass
    def validate_members(self, members): pass

class MessageFormatter:
    def format_success(self, action, details): pass
    def format_error(self, error): pass

class BotHandler:
    def __init__(self, parser, validator, formatter):
        self.parser = parser
        self.validator = validator
        self.formatter = formatter

    def handle_command(self, event): pass

2. Extract Method

When: A method is too long or does multiple things

# Before
def handle_time_command(event):
    parts = event.text.split()
    if len(parts) < 2:
        return "Error"
    time_str = parts[1]
    patterns = [r'^(\d{1,2}):(\d{2})$', r'^(\d{2})(\d{2})$']
    hour, minute = None, None
    for pattern in patterns:
        match = re.match(pattern, time_str)
        if match:
            hour = int(match.group(1))
            minute = int(match.group(2))
            break
    if not (0 <= hour <= 23):
        return "Hour error"
    # ... more logic

# After
def handle_time_command(event):
    time_str = extract_time_parameter(event.text)
    if not time_str:
        return format_missing_parameter_error()

    hour, minute, error = parse_time_flexible(time_str)
    if error:
        return error

    return update_schedule_time(event.group_id, hour, minute)

def extract_time_parameter(text: str) -> Optional[str]:
    parts = text.split(maxsplit=1)
    return parts[1] if len(parts) >= 2 else None

3. Introduce Parameter Object

When: Functions have too many parameters

# Before
def update_schedule(group_id, days, hour, minute, timezone, enabled):
    pass

# After
@dataclass
class ScheduleConfig:
    group_id: str
    days: str
    hour: int
    minute: int
    timezone: str = "Asia/Taipei"
    enabled: bool = True

def update_schedule(config: ScheduleConfig):
    pass

4. Replace Conditional with Polymorphism

When: Complex if/elif chains for different types

# Before
def format_message(message_type, data):
    if message_type == "success":
        return f"✅ {data['action']}\n{data['details']}"
    elif message_type == "error":
        return f"❌ {data['error']}\n{data['suggestion']}"
    elif message_type == "warning":
        return f"⚠️ {data['warning']}"

# After
class Message(ABC):
    @abstractmethod
    def format(self) -> str:
        pass

class SuccessMessage(Message):
    def __init__(self, action: str, details: dict):
        self.action = action
        self.details = details

    def format(self) -> str:
        return f"✅ {self.action}\n{self.details}"

class ErrorMessage(Message):
    def __init__(self, error: str, suggestion: str):
        self.error = error
        self.suggestion = suggestion

    def format(self) -> str:
        return f"❌ {self.error}\n{self.suggestion}"

📋 Refactoring Checklist

Before Refactoring

  • Write tests for existing functionality
  • Identify code smells (long methods, large classes, duplicate code)
  • Document current behavior
  • Create backup/branch

During Refactoring

  • Make small, incremental changes
  • Run tests after each change
  • Keep commits atomic and descriptive
  • Maintain backward compatibility if needed

After Refactoring

  • Verify all tests pass
  • Check performance hasn't degraded
  • Update documentation
  • Code review

🚨 Code Smells to Watch For

  1. Long Method (>20 lines) → Extract Method
  2. Large Class (>200 lines) → Extract Class
  3. Long Parameter List (>3 params) → Introduce Parameter Object
  4. Duplicate Code → Extract Method/Class
  5. Feature Envy (method uses another class more than its own) → Move Method
  6. Data Clumps (same group of data together) → Extract Class
  7. Primitive Obsession (using primitives instead of objects) → Introduce Value Object
  8. Switch Statements (type checking) → Replace with Polymorphism

🎯 Refactoring Priority for Current Codebase

High Priority

  1. Extract Command Handlers - Massive handle_message() function
  2. Separate Data Access - DataManager does too much
  3. Introduce Storage Abstraction - Tight coupling to Firebase

Medium Priority

  1. Extract Parsing Logic - Scattered parsing code
  2. Introduce Message Formatters - Duplicate formatting code
  3. Extract Validation - Validation mixed with business logic

Low Priority

  1. Introduce Value Objects - For ScheduleConfig, MemberGroup
  2. Extract Helper Functions - Utility functions in main file

📚 References


Last Updated: 2026-01-16 Maintainer: Code Quality Agent

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

38.63%
按下载量换算24

Claude

26.89%
按下载量换算17

Cursor

17.53%
按下载量换算11

Gemini CLI

8.88%
按下载量换算6

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

权限需确认

当前来源未能明确判断权限范围,默认进入异常复核队列。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills