سؤال

Let's say we have a DTO with 24 fields of type Long (one for each hour of the day). Most of the times, we need instances of DTO with zeros in all its fields. What we're doing right now looks quite long:

MyDTO day1 = new MyDTO();
day1.setQuantityHour1(new Long(0));
day1.setQuantityHour2(new Long(0));
day1.setQuantityHour3(new Long(0));
day1.setQuantityHour4(new Long(0));
...

Is it against the DTO pattern to include a constructor/factory method that provides already that?

هل كانت مفيدة؟

المحلول

No, I don't think there is anything wrong with a Factory Method (or, generally, a Creational Pattern) in this case. Generally, you want some sort of Creational Pattern to decouple the construction of an object from its functionality/business logic. In your case, being a DTO, you probably don't have business logic, but I don't think that makes using a Creational Pattern less appropriate if you have some complex build rules. A Builder Pattern may even work in this case. If construction is simple enough, put it in the Constructor.

نصائح أخرى

If you would use primitive type long in you DTO - they will be automatically initialized with 0L.

You can define all the instance variables as primitive data type long. So, when we create object, all the variables will be initialized by 0. The sample code is given below. package org.smarttechie;

public class SampleDTO {
    private long quantityHour1;
    private long quantityHour2;
    public long getQuantityHour1() {
        return quantityHour1;
    }
    public void setQuantityHour1(long quantityHour1) {
        this.quantityHour1 = quantityHour1;
    }
    public long getQuantityHour2() {
        return quantityHour2;
    }
    public void setQuantityHour2(long quantityHour2) {
        this.quantityHour2 = quantityHour2;
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top