dimanche 17 mai 2020

Optional vs exceptions, controllers vs services

I have JAVA design considerations: I'm struggling between choosing:

  1. services return Optional values and controllers handling the non-present case
  2. services handling directly the non-present case, return the real object if present and throw exceptions if not

Are there good practices to help me chose between the 2 approaches?

eg. Option 1 Controller:

public ResponseEntity<Product> findProductById(@PathVariable Long productId) {
        return this.productService.getProductById(productId).map(
                p -> ResponseEntity.ok(p)
        ).orElseThrow(() -> new ResourceNotFoundException(ResourceType.PRODUCT, "Id", productId.toString()));
    }

Service:

    public Optional<Product> getProductById(Long id) {
        return productRepository.findById(id).map(
                product -> someLogic(product)
        );
    }

Option 2: Controller

    public ResponseEntity<Product> findProductById(@PathVariable Long productId) {
        return ResponseEntity.ok(productService.getProductById(productId));
    }

Service

    public Product getProductById(Long id) {
        return productRepository.findById(id).map(
                product -> lazyLoadProduct(product)
        ).orElseThrow(() -> new ResourceNotFoundException(ResourceType.PRODUCT, "Id", id.toString()));;
    }

For both of these approaches, I have a ControllerAdvice which would eventually transform this Exception in a corresponding end-user-friendly message. So they both "work the same"

Aucun commentaire:

Enregistrer un commentaire