I'm currently working on a Spring Boot project where I have several REST endpoints defined within a controller class. While implementing these endpoints, I started wondering about the best practices for organizing code within these controller methods.
Specifically, I'm curious about the amount of code that should ideally be contained within a single controller method to maintain clean and readable code. Should each method strictly be a one-liner delegating functionality to service layer methods, or is it acceptable to have more complex logic within the controller methods themselves?
For example, consider the following method from my PersonController class:
@GetMapping(value = "/{id}")
@ResponseStatus(HttpStatus.OK)
public PersonResponse getPersonById(@PathVariable Long id) {
return personService.fetchPersonById(id);
}
I understand that this level of code organization is generally considered clean, but I'm uncertain about the acceptable amount of logic that can be included within a method while still adhering to the principles of clean code. What is the recommended approach for determining the threshold of complexity within controller methods?
I'd appreciate any insights or best practices regarding the organization of code within Spring Boot REST controllers. Thank you!
@ExceptionHandler
mechanisms, I would recommend using RestControllerAdvice
class to keep exception handling logic in one place for all endpoints.These recommendations help you to write clean, testable and maintainable API.