Token导航 LogoToken导航TokenDH.com
开发规范需要联网github未标认证来源可访问许可证需确认审计通过

java-best-practices-refactor-legacyJava 最佳实践 refactor legacy

Agent Skill

用于辅助 Java 项目开发、面向对象设计、Spring 生态、Maven 或 Gradle 依赖和后端工程实践。它适合让 Agent 分析类结构、设计接口、整理服务分层、生成测试或检查常见代码坏味道。使用时需要结合项目已有架构、包结构和依赖版本,不应只按通用教程改代码;涉及数据库、事务、并发或框架配置时,应先确认运行环境和回归测试范围。

总安装

220

周安装

9

GitHub Stars

1

下载量

71
CodexClaudeCursorGemini CLI

安装说明

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

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

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

请帮我安装这个 Agent Skill:java-best-practices-refactor-legacy(Java 最佳实践 refactor legacy)
来源仓库:https://github.com/dawiddutoit/custom-claude
仓库路径:skills/java-best-practices-refactor-legacy
安装命令:
npx skills add https://github.com/dawiddutoit/custom-claude --skill java-best-practices-refactor-legacy
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

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

skills.shnpx skills
npx skills add https://github.com/dawiddutoit/custom-claude --skill java-best-practices-refactor-legacy

简介

用于辅助 Java 项目开发、面向对象设计和 Spring 生态集成。

  • 适合分析类结构、设计接口、整理服务分层或生成测试代码。
  • 使用时需结合项目已有架构、包结构和依赖版本,避免仅按教程修改代码。
  • 涉及数据库、事务或并发配置时,应先确认运行环境和回归测试范围。
  • java-best-practices-refactor-legacy 属于开发规范类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

Java Legacy Code Refactoring

Quick Start

Point to any legacy Java file and receive a refactored version:

# Refactor a single legacy class
Refactor LegacyUserService.java to modern Java

# Refactor entire legacy package
Modernize all Java files in src/main/java/com/example/legacy/

When to Use

Use this skill when you need to:

  • Modernize pre-Java 8 code to use streams, lambdas, and Optional
  • Refactor legacy applications to modern Java patterns
  • Convert anonymous inner classes to lambda expressions
  • Replace imperative loops with Stream API
  • Apply SOLID principles to existing code
  • Extract methods from long methods (>50 lines)
  • Break up god classes into focused components
  • Replace null returns with Optional
  • Convert to try-with-resources for resource management
  • Apply design patterns (Strategy, Builder, etc.)
  • Migrate from old frameworks to modern alternatives
  • Improve error handling with custom exceptions

Instructions

Step 1: Analyze Legacy Code

Read the target file and identify legacy patterns:

Pre-Java 8 Patterns:

  • Anonymous inner classes instead of lambdas
  • Manual iteration instead of Stream API
  • Null checks instead of Optional
  • Manual resource management instead of try-with-resources
  • StringBuffer instead of StringBuilder
  • Vector/Hashtable instead of modern collections

Code Smells:

  • God classes (classes doing too much)
  • Long methods (over 50 lines)
  • Deep nesting (over 3 levels)
  • Code duplication
  • Poor naming
  • Magic numbers and strings
  • Tight coupling

Anti-Patterns:

  • Singleton abuse
  • Service locator pattern
  • God objects
  • Anemic domain models
  • Transaction script pattern

Step 2: Plan Refactoring Strategy

Prioritize refactorings by impact and risk:

High Priority (High Impact, Low Risk):

  1. Extract constants for magic numbers/strings
  2. Rename poorly named variables/methods
  3. Convert to try-with-resources
  4. Replace StringBuffer with StringBuilder

Medium Priority (High Impact, Medium Risk):

  1. Convert loops to Stream API
  2. Replace null returns with Optional
  3. Extract methods from long methods
  4. Apply design patterns

Low Priority (Medium Impact, High Risk):

  1. Extract classes from god classes
  2. Restructure architecture
  3. Change public APIs

Step 3: Apply Modern Java Features

Lambda Expressions:

// Before: Anonymous inner class
Comparator<User> comparator = new Comparator<User>() {
    @Override
    public int compare(User u1, User u2) {
        return u1.getName().compareTo(u2.getName());
    }
};

// After: Lambda and method reference
Comparator<User> comparator = Comparator.comparing(User::getName);

Stream API:

// Before: Imperative loops
List<String> names = new ArrayList<>();
for (User user : users) {
    if (user.isActive()) {
        names.add(user.getName().toUpperCase());
    }
}
Collections.sort(names);

// After: Functional streams
List<String> names = users.stream()
    .filter(User::isActive)
    .map(User::getName)
    .map(String::toUpperCase)
    .sorted()
    .toList();

Optional:

// Before: Null returns
public User findUser(String id) {
    User user = repository.findById(id);
    return user != null ? user : DEFAULT_USER;
}

// After: Optional
public Optional<User> findUser(String id) {
    return repository.findById(id);
}

// Usage
User user = findUser(id).orElse(DEFAULT_USER);

Records (Java 14+):

// Before: Boilerplate DTO
public class UserDTO {
    private final String name;
    private final String email;
    // constructor, getters, equals, hashCode...
}

// After: Record
public record UserDTO(String name, String email) {}

Try-with-resources:

// Before: Manual resource management
BufferedReader reader = null;
try {
    reader = new BufferedReader(new FileReader("file.txt"));
    // use reader
} finally {
    if (reader != null) {
        try { reader.close(); } catch (IOException e) {}
    }
}

// After: Try-with-resources
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
    // use reader
} catch (IOException e) {
    log.error("Failed to read file", e);
}

Step 4: Extract Methods and Classes

Extract Method:

// Before: Long method
public void processOrder(Order order) {
    // Validation (20 lines)
    // Calculate total (15 lines)
    // Save order (10 lines)
}

// After: Extracted methods
public void processOrder(Order order) {
    validateOrder(order);
    double total = calculateTotal(order);
    saveOrder(order, total);
}

Extract Class:

// Before: God class
public class OrderProcessor {
    public void processOrder(Order order) { /* ... */ }
    public void validateOrder(Order order) { /* ... */ }
    public double calculateTotal(Order order) { /* ... */ }
    public void sendEmail(Order order) { /* ... */ }
    public void updateInventory(Order order) { /* ... */ }
}

// After: Separated responsibilities
public class OrderProcessor {
    private final OrderValidator validator;
    private final OrderCalculator calculator;
    private final OrderNotifier notifier;
    private final InventoryManager inventory;

    public void processOrder(Order order) {
        validator.validate(order);
        double total = calculator.calculateTotal(order);
        order.setTotal(total);
        inventory.updateInventory(order);
        notifier.sendOrderConfirmation(order);
    }
}

Step 5: Apply Design Patterns

See references/design-patterns.md for:

  • Strategy pattern for conditional logic
  • Builder pattern for complex objects
  • Factory pattern for object creation
  • Repository pattern for data access

Step 6: Improve Error Handling

Replace printStackTrace with Logging:

// Before
try {
    processPayment(order);
} catch (Exception e) {
    e.printStackTrace();
}

// After
try {
    processPayment(order);
} catch (PaymentException e) {
    log.error("Payment processing failed for order {}", order.getId(), e);
    throw new OrderProcessingException("Failed to process order payment", e);
}

Create Custom Exceptions:

public class UserNotFoundException extends RuntimeException {
    public UserNotFoundException(Long id) {
        super("User not found with ID: " + id);
    }
}

Supporting Files

Requirements

Tools Needed

  • Java 8+ (for lambdas, streams, Optional)
  • Java 11+ (for var, improved String methods)
  • Java 14+ (for records, switch expressions)
  • Java 17+ (for sealed classes, pattern matching)
  • Modern IDE with refactoring support

Dependencies

<!-- Lombok (for reducing boilerplate) -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.30</version>
    <scope>provided</scope>
</dependency>

<!-- SLF4J for logging -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>2.0.9</version>
</dependency>

Refactoring Checklist

Before refactoring:

  • Ensure tests exist (or create them first)
  • Understand the current behavior completely
  • Create a backup or commit current state

During refactoring:

  • Make one change at a time
  • Run tests after each change
  • Keep commits small and focused

After refactoring:

  • Verify all tests pass
  • Check for performance regressions
  • Review code with team

Output Format

When refactoring, provide:

  1. Analysis of legacy code issues
  2. Refactoring plan with prioritized changes
  3. Refactored code with detailed explanations
  4. Before/After comparison highlighting improvements
  5. Testing recommendations for validation

Red Flags to Avoid

  • Never refactor code without understanding its purpose
  • Never refactor without tests to validate behavior
  • Avoid changing multiple patterns simultaneously
  • Don't optimize prematurely
  • Don't refactor code you can't test
  • Never break public APIs without migration strategy

Notes

  • Focus on one refactoring pattern at a time
  • Prioritize safety over cleverness
  • Maintain backward compatibility when possible
  • Document breaking changes clearly
  • Run full test suite after each refactoring step

适合场景

01

用户想查找某类 Agent Skill 时

02

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

03

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

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

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

能力 4

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

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

平台分布

Codex

35.27%
按下载量换算25

Claude

31.72%
按下载量换算23

Cursor

20.62%
按下载量换算15

Gemini CLI

9.76%
按下载量换算7

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

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

来源信息

继续浏览同类 Skills