Skip to content

Migrate validations from Services to Controllers layer #182

@nanotaboada

Description

@nanotaboada

Description

Currently, the validation of BookDTO objects using the javax.validation.Validator is handled within the BooksService. To follow better separation of concerns and align with typical REST API architecture, validation logic should be moved to the BooksController. This change will allow the service layer to focus purely on business logic and reduce its responsibility for request integrity.

This refactor will also improve testability and enable automatic HTTP 400 responses via @Valid, leveraging Spring's standard validation mechanisms.

Suggested Approach

1. Update Controller

Use @Valid on the DTO argument in controller methods:

@PostMapping
public ResponseEntity<Void> create(@RequestBody @Valid BookDTO bookDTO) {
    boolean created = booksService.create(bookDTO);
    return created ? ResponseEntity.status(HttpStatus.CREATED).build()
                   : ResponseEntity.status(HttpStatus.CONFLICT).build();
}

@PutMapping
public ResponseEntity<Void> update(@RequestBody @Valid BookDTO bookDTO) {
    boolean updated = booksService.update(bookDTO);
    return updated ? ResponseEntity.ok().build()
                   : ResponseEntity.notFound().build();
}

2. Remove Validator from Service

Eliminate the manual call to validator.validate(bookDTO) inside the service methods.

3. Handle Validation Exceptions (Optional)

To customize validation error responses, implement an exception handler:

@RestControllerAdvice
public class ValidationExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<String> handleValidationError(MethodArgumentNotValidException ex) {
        return ResponseEntity.badRequest().body("Invalid input: " +
            ex.getBindingResult().getFieldErrors().stream()
                .map(err -> err.getField() + " " + err.getDefaultMessage())
                .collect(Collectors.joining(", "))
        );
    }
}

Acceptance Criteria

  • Remove explicit javax.validation.Validator usage from BooksService.
  • Add @Valid annotation to @RequestBody parameters in the controller methods for create and update.
  • Ensure invalid input is handled automatically by Spring (400 Bad Request).
  • Adjust or remove service-level tests that simulate validation errors.
  • Add or update controller tests to cover invalid request scenarios.
  • Ensure all existing valid/invalid use cases continue to return the appropriate HTTP responses.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestjavaPull requests that update Java code

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions