一键导入
clean-code
SOLID principles, clean code practices, and refactoring patterns for Java applications
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
SOLID principles, clean code practices, and refactoring patterns for Java applications
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Use when implementing Spring Boot 3.x applications. Provides hands-on implementation patterns for web, data, security, testing, and cloud-native development.
Review REST API contracts for HTTP semantics, versioning, backward compatibility, and response consistency. Use when user asks "review API", "check endpoints", "REST review", or before releasing API changes.
Use when designing Spring Boot 3.x application architecture, making technology decisions, or planning project structure. Provides architectural patterns and references for project setup, JPA, security, testing, and reactive programming.
Use when designing, reviewing, or modifying REST API endpoints to enforce proper HTTP verbs, status codes, versioning, and API contract best practices.
Use when reviewing or writing code to enforce DRY, KISS, and YAGNI principles with Java-specific guidance.
Use when implementing or reviewing code that benefits from established design patterns like Builder, Factory, Strategy, Observer, Decorator, or Adapter.
| name | clean-code |
| description | SOLID principles, clean code practices, and refactoring patterns for Java applications |
Each class should have only one reason to change.
// BAD: class handles both order logic and email sending
public class OrderService {
public Order createOrder(CreateOrderRequest request) { /* ... */ }
public void sendOrderConfirmationEmail(Order order) { /* ... */ }
}
// GOOD: responsibilities separated
public class OrderService {
private final OrderNotificationService notificationService;
public Order createOrder(CreateOrderRequest request) {
var order = processOrder(request);
notificationService.notifyOrderCreated(order);
return order;
}
}
public class OrderNotificationService {
private final EmailService emailService;
public void notifyOrderCreated(Order order) {
emailService.send(buildConfirmationEmail(order));
}
}
Open for extension, closed for modification.
// GOOD: strategy pattern for discount calculation
public interface DiscountStrategy {
BigDecimal calculateDiscount(Order order);
}
@Component
public class VolumeDiscountStrategy implements DiscountStrategy {
@Override
public BigDecimal calculateDiscount(Order order) {
if (order.getItemCount() > 10) {
return order.getTotal().multiply(new BigDecimal("0.10"));
}
return BigDecimal.ZERO;
}
}
@Component
public class LoyaltyDiscountStrategy implements DiscountStrategy {
@Override
public BigDecimal calculateDiscount(Order order) {
if (order.getCustomer().isLoyal()) {
return order.getTotal().multiply(new BigDecimal("0.05"));
}
return BigDecimal.ZERO;
}
}
@Service
public class DiscountService {
private final List<DiscountStrategy> strategies;
public BigDecimal calculateTotalDiscount(Order order) {
return strategies.stream()
.map(s -> s.calculateDiscount(order))
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
}
Subtypes must be substitutable for their base types.
// BAD: Square violates Rectangle's contract
public class Rectangle {
public void setWidth(int w) { this.width = w; }
public void setHeight(int h) { this.height = h; }
}
// GOOD: use immutable records or separate hierarchies
public sealed interface Shape permits Rectangle, Square, Circle {
double area();
}
public record Rectangle(double width, double height) implements Shape {
public double area() { return width * height; }
}
public record Square(double side) implements Shape {
public double area() { return side * side; }
}
Prefer small, focused interfaces.
// BAD: fat interface
public interface UserService {
User findById(String id);
List<User> findAll();
void createUser(User user);
void deleteUser(String id);
void sendWelcomeEmail(User user);
void generateReport(User user);
}
// GOOD: segregated interfaces
public interface UserReadService {
User findById(String id);
List<User> findAll();
}
public interface UserWriteService {
void createUser(User user);
void deleteUser(String id);
}
Depend on abstractions, not concretions.
// GOOD: service depends on interface, not implementation
@Service
public class PaymentService {
private final PaymentGateway paymentGateway; // interface
public PaymentResult processPayment(PaymentRequest request) {
return paymentGateway.charge(request);
}
}
// Infrastructure adapter implements the interface
@Component
@Profile("production")
public class StripePaymentGateway implements PaymentGateway {
@Override
public PaymentResult charge(PaymentRequest request) { /* ... */ }
}
// BAD
int d; // elapsed time in days
List<int[]> list1;
public void process(Map<String, Object> m) {}
// GOOD
int elapsedDays;
List<Cell> flaggedCells;
public void processPayment(Map<String, PaymentDetail> paymentsByOrderId) {}
// BAD: method doing too many things
public void processOrder(Order order) {
// validate (10 lines)
// calculate totals (15 lines)
// apply discounts (10 lines)
// persist (5 lines)
// send notification (10 lines)
}
// GOOD: each step is its own method
public void processOrder(Order order) {
validateOrder(order);
var totals = calculateTotals(order);
var finalAmount = applyDiscounts(order, totals);
persistOrder(order, finalAmount);
notifyOrderCreated(order);
}
// BAD: returning null
public User findUser(String id) {
return userMap.get(id); // might be null
}
// GOOD: use Optional
public Optional<User> findUser(String id) {
return Optional.ofNullable(userMap.get(id));
}
// GOOD: return empty collections instead of null
public List<Order> findOrders(String customerId) {
var orders = orderRepository.findByCustomerId(customerId);
return orders != null ? orders : List.of();
}