home / skills / leavesfly / jimi / java-best-practices

This skill helps you apply Java best practices and design patterns, including clean naming, streams, and robust error handling.

npx playbooks add skill leavesfly/jimi --skill java-best-practices

Review the files below or copy the command above to add this skill to your agents.

Files (2)
SKILL.md
1.7 KB
---
name: java-best-practices
description: Java 编码最佳实践与设计模式
version: 1.0.0
category: development
triggers:
  - java best practice
  - Java 最佳实践
  - 设计模式
  - Java 编码规范
scriptPath: check-java-env.sh
scriptType: bash
autoExecute: true
scriptTimeout: 5
---

# Java 最佳实践技能包

## 编码规范

### 命名规范
- **类名**:PascalCase(UserService)
- **方法/变量**:camelCase(getUserById)
- **常量**:UPPER_SNAKE_CASE(MAX_SIZE)
- **包名**:小写(com.example.service)

### 常用设计模式

**单例模式(枚举实现)**:
```java
public enum Singleton {
    INSTANCE;
    public void doSomething() {}
}
```

**工厂模式**:
```java
public class UserFactory {
    public static User createUser(String type) {
        return switch (type) {
            case "admin" -> new AdminUser();
            case "guest" -> new GuestUser();
            default -> new RegularUser();
        };
    }
}
```

**Builder 模式**:
```java
User user = User.builder()
    .name("张三")
    .age(25)
    .build();
```

## Stream API

```java
List<String> names = users.stream()
    .filter(u -> u.getAge() > 18)
    .map(User::getName)
    .collect(Collectors.toList());
```

## 异常处理

```java
try {
    // 业务逻辑
} catch (SpecificException e) {
    log.error("Error: {}", e.getMessage(), e);
    throw new BusinessException("操作失败");
} finally {
    // 清理资源
}
```

## 并发编程

```java
ExecutorService executor = Executors.newFixedThreadPool(10);
executor.submit(() -> {
    // 异步任务
});
```

## Optional 使用

```java
Optional<User> user = userRepository.findById(id);
return user.orElseThrow(() -> new NotFoundException());
```

Overview

This skill collects practical Java coding conventions, common design patterns, and concise examples for robust application development. It focuses on naming, exception handling, concurrency, Stream API, Optional usage, and patterns like Singleton, Factory, and Builder. Use it to standardize code style and apply proven patterns across projects.

How this skill works

The skill inspects common Java development areas and presents clear, actionable snippets and rules you can apply immediately. It highlights naming conventions, pattern choices, Stream and Optional idioms, exception handling structure, and basic concurrency setups. Each item is framed to reduce bugs, improve readability, and encourage maintainable designs.

When to use it

  • Onboard new Java developers to a unified style guide
  • Design or refactor modules to apply appropriate design patterns
  • Implement safe exception handling and error translation
  • Introduce functional-style processing with Stream API
  • Add concurrency or asynchronous tasks to backend services

Best practices

  • Use PascalCase for class names, camelCase for methods and variables, and UPPER_SNAKE_CASE for constants
  • Prefer enum-based Singleton for thread-safe single-instance needs
  • Encapsulate complex object creation with Factory or Builder patterns to simplify clients
  • Use Stream API for readable collection processing and avoid mutable external state in lambdas
  • Catch specific exceptions, log with context, and rethrow domain-specific exceptions; always clean up resources
  • Use Optional to represent absent values and orElseThrow to convert missing data to explicit errors

Example use cases

  • Create a single, thread-safe service instance using enum Singleton for configuration access
  • Provide a UserFactory that returns different user implementations based on type input
  • Build complex DTOs or entities with a Builder to keep constructors manageable
  • Process collections of users with Stream filter-map-collect to produce lists of names or summaries
  • Run background tasks with a fixed thread pool ExecutorService and submit Runnables or Callables

FAQ

When should I use Builder vs constructor?

Use Builder when an object has many optional fields or when constructor parameter lists become hard to read. Use constructors for simple, mandatory fields for clarity.

Is enum Singleton always best?

Enum Singleton is simple and serialization-safe for single-instance needs. For lazy initialization or dependency-injected singletons, prefer framework-managed singletons or other patterns.