java-best-practices
Java 编码最佳实践与设计模式
When & Why to Use This Skill
This Claude skill provides a comprehensive framework for Java development excellence, focusing on industry-standard coding best practices and essential design patterns. It empowers developers to write clean, maintainable, and high-performance Java code by providing guidance on naming conventions, modern API usage (Stream, Optional), and robust architectural patterns like Singleton and Builder.
Use Cases
- Automated Code Quality Audits: Use the skill to evaluate Java source code against standard naming conventions and structural best practices to ensure consistency across large-scale projects.
- Architectural Pattern Implementation: Quickly generate and implement robust design patterns such as Factory, Builder, and Singleton to solve complex object creation and structural challenges.
- Legacy Code Modernization: Assist in refactoring older Java applications by integrating modern features like the Stream API for efficient data processing and Optional for safer null handling.
- Standardized Exception Management: Establish and enforce consistent error handling and resource management strategies to improve application stability and simplify debugging processes.
| name | java-best-practices |
|---|---|
| description | Java 编码最佳实践与设计模式 |
| version | 1.0.0 |
| category | development |
| scriptPath | check-java-env.sh |
| scriptType | bash |
| autoExecute | true |
| scriptTimeout | 5 |
Java 最佳实践技能包
编码规范
命名规范
- 类名:PascalCase(UserService)
- 方法/变量:camelCase(getUserById)
- 常量:UPPER_SNAKE_CASE(MAX_SIZE)
- 包名:小写(com.example.service)
常用设计模式
单例模式(枚举实现):
public enum Singleton {
INSTANCE;
public void doSomething() {}
}
工厂模式:
public class UserFactory {
public static User createUser(String type) {
return switch (type) {
case "admin" -> new AdminUser();
case "guest" -> new GuestUser();
default -> new RegularUser();
};
}
}
Builder 模式:
User user = User.builder()
.name("张三")
.age(25)
.build();
Stream API
List<String> names = users.stream()
.filter(u -> u.getAge() > 18)
.map(User::getName)
.collect(Collectors.toList());
异常处理
try {
// 业务逻辑
} catch (SpecificException e) {
log.error("Error: {}", e.getMessage(), e);
throw new BusinessException("操作失败");
} finally {
// 清理资源
}
并发编程
ExecutorService executor = Executors.newFixedThreadPool(10);
executor.submit(() -> {
// 异步任务
});
Optional 使用
Optional<User> user = userRepository.findById(id);
return user.orElseThrow(() -> new NotFoundException());