3

I wonder where to add method that reads my dto WindowDto.getPath().getPoints() and based on this collections returns some value (that value will be needed in some different srevices in my app):

public class WindowDto{

    @JsonProperty("valid_from")
    @JsonDeserialize(using = LocalDateDeserializer.class)
    private LocalDate validFrom;

    @JsonProperty("valid_to")
    @FutureOrPresent
    @JsonDeserialize(using = LocalDateDeserializer.class)
    private LocalDate validTo;

    @JsonProperty("type")
    private String type;

    @JsonProperty("path")
    @Valid
    private PathDto path;

    @Data
    public static class PathDto {
        @JsonProperty("points")
        private Set<PointDto> points;
    }

//maybe here my helper method
public Long getStoreId(){
//iterate over points and make some pure operations on this collection without using any repository etc...
}

Is it good practice to add such helper method in DTO? Or maybe create some other static class like WindowDtoHelper?

2 Answers 2

5

Do not get too hung up on DTOs being "property bags." When in doubt, fall back on good ol' fashioned Object-Oriented Programming. Classes bundle data and behavior. Your DTO needs some behavior. Add those methods to the class as long as you do not embed logic in the DTO that conceptually belongs in a different layer.

A DTO can have lots of null values. If you need to operate on a collection, and you pepper your code with a bunch of null-checks, adding a method to the DTO can help clean that up by centralizing the null-checks. Maybe worse case scenario you return an empty collection or Optional<T> from that method.

1

I disagree with Greg Burghardt. DTO stands for data transfer object. Not for data calculation object. If you want to calculate something inside your DTO, why not pass (or keep) this calculation in one additional field? (during construction)

In addition, I agree with what Victor Rentea said in Evolving a Clean, Pragmatic Architecture (also in youtube) about having public fields in DTO. He proposes public fields for the same reason I mentioned above. DTOs should be as dumb as it gets - just a bunch of properties in public fields.

1
  • While I agree that there's nothing inherently wrong with data-only DTOs, I don't quite agree that DTO's are therefore not allowed to contain anything else. Even a simple public string Initials => this.FirstName.Substring(1) + this.LastName.Substring(1) would count as "logic, not data", but I think things like these are perfectly fine to be in a DTO themselves.
    – Flater
    Feb 16, 2021 at 10:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.