Coding Standards
Naming Conventions
- Class Names:PascalCase(UserService)
- Methods/Variables:camelCase(getUserById)
- Constants:UPPER_SNAKE_CASE(MAX_SIZE)
- Package Names: lowercase (com.example.service)
Common Design Patterns
Singleton Pattern (Enum Implementation):
public enum Singleton {
INSTANCE;
public void doSomething() {}
}
Factory Pattern:
public class UserFactory {
public static User createUser(String type) {
return switch (type) {
case "admin" -> new AdminUser();
case "guest" -> new GuestUser();
default -> new RegularUser();
};
}
}
Builder Pattern:
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());
Exception Handling
try {
// 业务逻辑
} catch (SpecificException e) {
log.error("Error: {}", e.getMessage(), e);
throw new BusinessException("操作失败");
} finally {
// 清理资源
}
Concurrent Programming
ExecutorService executor = Executors.newFixedThreadPool(10);
executor.submit(() -> {
// 异步任务
});
Using Optional
Optional<User> user = userRepository.findById(id);
return user.orElseThrow(() -> new NotFoundException());