Skip to content

Instantly share code, notes, and snippets.

@stevenwaterman
Created December 27, 2019 14:09
Embed
What would you like to do?
Perfect Spring DTO (Normal)
package com.scottlogic.springdto;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Positive;
import lombok.Value;
public class Example {
@Value public static class CreateProductRequest{
/**
* The product's name as should appear on the site.
* Any capitalisation here should be stored in the
* database but any filtering should be case-insensitive.
*/
@NotBlank
String name;
/**
* The amount that we sell a product for in GBP.
* This includes our margin but should not include
* any delivery fees or VAT.
*/
@Positive
Double price;
/**
* The amount that it costs us to purchase this product
* For the amount we sell a product for, see the Price.
* <b>This data is confidential</b>
*/
@Positive
Double cost;
}
@Value public static class ProductResponse{
/**
* The identifier for this product.
* IDs are unique amongst products but may be
* repeated across other entity types
*/
@Positive
Long id;
/**
* The product's name as should appear on the site.
* Any capitalisation here should be stored in the
* database but any filtering should be case-insensitive.
*/
@NotBlank
String name;
/**
* The amount that we sell a product for in GBP.
* This includes our margin but should not include
* any delivery fees or VAT.
*/
@Positive
Double price;
}
@Value public static class PrivateProductResponse{
/**
* The product's name as should appear on the site.
* Any capitalisation here should be stored in the
* database but any filtering should be case-insensitive.
*/
@NotBlank
Long id;
/**
* The product's name as should appear on the site.
* Any capitalisation here should be stored in the
* database but any filtering should be case-insensitive.
*/
@NotBlank
String name;
/**
* The amount that we sell a product for in GBP.
* This includes our margin but should not include
* any delivery fees or VAT.
*/
@Positive
Double price;
/**
* The amount that it costs us to purchase this product
* For the amount we sell a product for, see the Price.
* <b>This data is confidential</b>
*/
@Positive
Double cost;
}
private static Double getMarkup(Double price, Double cost){
return (price - cost) / cost;
}
public static Double getMarkup(CreateProductRequest dto){
return getMarkup(dto.getPrice(), dto.getCost());
}
public static Double getMarkup(PrivateProductResponse dto){
return getMarkup(dto.getPrice(), dto.getCost());
}
}
@MattCline-SL
Copy link

Why bother with validation annotations on the response objects? Nothing should be validating the response because you are creating it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment