Paperless / rebuild
Course 2 28ef273

controllers.md

docs/controllers.md

Snapshot 28ef273Download original
1# Controllers23## HTTP Edge Responsibility45Think of `<Feature>Controller` as the HTTP edge and nothing more:6- Maps request DTOs to domain models.7- Calls the service interface.8- Maps domain model results to response DTOs.9- **No business logic:** Keep controllers completely free of domain logic.10- **No existence checks:** Never write `findById(...).isPresent()` in controllers — missing resources must throw exceptions from the service layer.11- **No local `@ExceptionHandler`:** Exception handling belongs exclusively in `GlobalExceptionHandler` (`@ControllerAdvice`).1213## Separate Mapping Statements1415Every mapping is its own statement assigned to a `var` local variable, and the service invocation is its own statement too:1617```java18@PostMapping19@ResponseStatus(HttpStatus.CREATED)20public TaskDTO createTask(@RequestBody @Valid CreateTaskDTO dto) {21    var task = TaskMapper.toModel(dto);22    var created = taskService.create(task);23    return TaskMapper.toDto(created);24}25```2627Never nest mappings inside service calls or vice-versa — nesting saves a couple lines but destroys debugger step-through:2829```java30// ✗ nested mapping — request-map buried in argument list, response-map wrapping the call31return TaskMapper.toDto(taskService.create(TaskMapper.toModel(dto)));32```3334## Request Parameters & Search Endpoints3536- **Filtering:** 1 or 2 filter parameters are fine as individual `@RequestParam` arguments. 3 or more parameters (e.g., dates, status enums, keyword search) deserve a dedicated filter object bound via `@ModelAttribute`.37- **Paged searches:** Accept a `Pageable` and return a standard list envelope (e.g. `{ metaData, data }`).38- **Endpoint naming:** Name search handler methods and their service methods `search...` (e.g. `searchTasks`), never `list...`, even when no filter is provided.3940## HTTP Status Codes4142- `HttpStatus.CREATED` (201): On resource creation (`@ResponseStatus(HttpStatus.CREATED)`).43- `HttpStatus.NO_CONTENT` (204): On resource deletion (`@ResponseStatus(HttpStatus.NO_CONTENT)`).44- Defaults to 200 OK for standard queries and updates.4546## Controller Checklist4748Before committing any controller method, verify:49- [ ] `var` for local variables only — no `final`, no explicit types.50- [ ] Request mapping → service call → response mapping are separate statements.51- [ ] No mapper call nested inside a service call or another mapper call.52- [ ] No repository interactions or existence checks (`findById().isPresent()`).53

Search chapters, reference and source filenames.