Code Quality

Long Java Methods: Apply Extract Method Refactoring

Methods over 20-30 lines violate the Single Responsibility Principle. In Java, the Extract Method refactoring is a one-keystroke operation in IntelliJ (Ctrl+Alt+M).


❌ Overly Long Service Method

public OrderResponse createOrder(CreateOrderRequest request) {
    if (request.getUserId() == null) throw new ValidationException('userId required');
    if (request.getItems() == null || request.getItems().isEmpty())
        throw new ValidationException('items required');
    User user = userRepo.findById(request.getUserId())
        .orElseThrow(() -> new NotFoundException('User not found'));
    BigDecimal total = request.getItems().stream()
        .map(i -> i.getPrice().multiply(BigDecimal.valueOf(i.getQty())))
        .reduce(BigDecimal.ZERO, BigDecimal::add);
    Order order = new Order(user, total, request.getItems());
    orderRepo.save(order);
    emailService.sendOrderConfirmation(user.getEmail(), order);
    return new OrderResponse(order.getId(), total);
}

✅ Extracted Methods

public OrderResponse createOrder(CreateOrderRequest request) {
    validateCreateOrderRequest(request);
    User user         = loadUser(request.getUserId());
    BigDecimal total  = calculateTotal(request.getItems());
    Order order       = saveOrder(user, total, request.getItems());
    sendConfirmation(user, order);
    return new OrderResponse(order.getId(), total);
}
private BigDecimal calculateTotal(List<OrderItem> items) { ... }
private void validateCreateOrderRequest(CreateOrderRequest r) { ... }
💡

Pro tip: Each extracted method can now be unit tested independently without mocking the entire order creation flow.

Paste this code into LearnCodeGuide

Detect Java vulnerabilities and bugs automatically with AI-powered analysis.

Analyze Java Code →

Related Guides

Java Duplicate CodeJava Dead CodeJava Magic Numbers