Katkat

Review a Spring REST Controller for Correctness and Per-Request Waste

SchwabJava Developer · Onsite

Last updated

Analyze a flawed Spring Boot REST controller to identify anti-patterns, HTTP status code misuses, concurrency hazards, and unnecessary per-request object allocations. Refactor the implementation to follow production-grade enterprise standards.

Scenario

You are performing a code review for an internal portfolio management service at a financial brokerage. A junior engineer has submitted the following Spring Boot REST controller responsible for executing stock order placements and fetching order histories.

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @Autowired
    private OrderRepository orderRepository;

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @PostMapping("/create")
    public ResponseEntity placeOrder(@RequestBody OrderRequest request) {
        // Heavy client created on every incoming request
        PricingClient pricingClient = new PricingClient();
        
        if (request.getQuantity() <= 0) {
            return ResponseEntity.status(500).body("Quantity must be positive");
        }

        double currentPrice = pricingClient.getQuote(request.getTicker());
        Order order = new Order();
        order.setTicker(request.getTicker());
        order.setQuantity(request.getQuantity());
        order.setExecutedPrice(currentPrice);
        order.setTimestamp(dateFormat.format(new Date()));

        orderRepository.save(order);
        return ResponseEntity.status(200).body("Order placed successfully");
    }

    @GetMapping("/history/{accountId}")
    public List getHistory(@PathVariable String accountId) {
        try {
            return orderRepository.findAllByAccountId(accountId);
        } catch (Exception e) {
            return new ArrayList();
        }
    }
}

Task

  1. Identify Bugs & Anti-Patterns: Identify at least 5 distinct issues across thread safety, HTTP semantics, layer abstraction, exception handling, resource allocation, and scalability.
  2. Propose the Refactored Design: Describe how each issue should be resolved following modern Spring Boot best practices (e.g., dependency injection, @ControllerAdvice, input validation, and pagination).
  3. Refactor the Code: Provide a clean, idiomatic version of the controller and any supporting error-handling advice.

Hints

Hint 1

Look closely at the member variables in the singleton-scoped controller: `SimpleDateFormat` is notoriously not thread-safe.

Hint 2

Examine how dependencies are managed inside the method bodies versus constructor injection, and consider the overhead of instantiating external network clients on each request.

Hint 3

Inspect the HTTP response codes, query unpaginated collection sizes, and how exceptions are swallowed rather than mapped to standard error envelopes.

Follow-up questions

  • How would you implement idempotent request handling for `placeOrder` to prevent accidental duplicate order submissions caused by network retries?
  • How would you test this controller using `@WebMvcTest` and `MockMvc` without starting the entire Spring application context or connecting to a database?
  • If `pricingClient.getQuote(...)` experiences transient latency, how would you configure timeouts and circuit breakers using Resilience4j or Spring WebClient?