Java coding standards

From xu-xiang/everything-claude-code-zh · View interactive version

Java coding standards is an AI agent skill from the GitHub repository xu-xiang/everything-claude-code-zh. Spring Boot 服务的 Java 编码规范:命名、不可变性、Optional 使用、流(streams)、异常、泛型以及项目布局。

How to use this skill

Skill file

Java 编码规范 (Java Coding Standards)

适用于 Spring Boot 服务中可读、可维护的 Java (17+) 代码规范。

何时激活 (When to Activate)

核心原则 (Core Principles)

命名 (Naming)

// ✅ 类/Records:大驼峰(PascalCase)
public class MarketService {}
public record Money(BigDecimal amount, Currency currency) {}

// ✅ 方法/字段:小驼峰(camelCase)
private final MarketRepository marketRepository;
public Market findBySlug(String slug) {}

// ✅ 常量:全大写蛇形(UPPER_SNAKE_CASE)
private static final int MAX_PAGE_SIZE = 100;

不可变性 (Immutability)

// ✅ 优先使用 records 和 final 字段
public record MarketDto(Long id, String name, MarketStatus status) {}

public class Market {
  private final Long id;
  private final String name;
  // 仅提供 getter,不提供 setter
}

Optional 使用 (Optional Usage)

// ✅ find* 方法应返回 Optional
Optional<Market> market = marketRepository.findBySlug(slug);

// ✅ 使用 Map/flatMap 替代 get()
return market
    .map(MarketResponse::from)
    .orElseThrow(() -> new EntityNotFoundException("Market not found"));

流最佳实践 (Streams Best Practices)

// ✅ 使用流进行转换,保持流水线简短
List<String> names = markets.stream()
    .map(Market::name)
    .filter(Objects::nonNull)
    .toList();

// ❌ 避免复杂的嵌套流;为了清晰起见,优先使用循环

异常处理 (Exceptions)

throw new MarketNotFoundException(slug);

泛型与类型安全 (Generics and Type Safety)

public <T extends Identifiable> Map<Long, T> indexById(Collection<T> items) { ... }

项目结构 (Project Structure - Maven/Gradle)

src/main/java/com/example/app/
  config/
  controller/
  service/
  repository/
  domain/
  dto/
  util/
src/main/resources/
  application.yml
src/test/java/... (与 main 结构镜像)

格式与风格 (Formatting and Style)

应避免的代码异味 (Code Smells to Avoid)

日志记录 (Logging)

private static final Logger log = LoggerFactory.getLogger(MarketService.class);
log.info("fetch_market slug={}", slug);
log.error("failed_fetch_market slug={}", slug, ex);

空值处理 (Null Handling)

测试期望 (Testing Expectations)

记住:保持代码有明确意图、强类型且可观测。除非证明确有必要,否则应优先考虑可维护性,而非微优化。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.