Business logic in domain objects

The presence of this class:

public class DataPeriod {

private final String key;
private final LocalDate from;
private final LocalDate to;

private final Map<LocalDate, DataPoint> dataPoints = new HashMap<LocalDate, DataPoint>();

public DataPeriod(String key, LocalDate from, LocalDate to) {
    this.key = key;
    this.from = from;
    this.to = to;
}

public LocalDate getFrom() {
    return from;
}

public LocalDate getTo() {
    return to;
}

public void hit(int id) {
    DataPoint dataPoint = getOrCreate();
    dataPoint.hit(id);
}

private DataPoint getOrCreate() {
    LocalDate now = LocalDate.now();
    String dataPointKey = key + now.toString();
    if ( !dataPoints.containsKey(now) ) {
        DataPoint dataPoint = new DataPoint(dataPointKey);
        dataPoints.put(now, dataPoint);
    }

    return dataPoints.get(dataPointKey);
}

public long count() {
    long count = 0l;
    for (DataPoint dataPoint : dataPoints.values()) {
        count += dataPoint.count();
    }
    return count;
}

      

It may be a good idea to remove the methods hit(int id)

and getOrCreate()

in any other class as a service or an assistant. But then they must be changed to get the parameter for DataPoint

.

I think the point is to include them in the class DataPoint

because they represent actions that the class should know DataPeriod

.

Is there some kind of pattern for this scenario? In terms of concurrency, is it meaningless to extract or not extract these methods?

+3


source to share


1 answer


I think it is better to leave the methods in the same class of the model if they only use data within the same class, or in other words, if they do not depend on other classes.

Of course, you will never access services from a model class, but sometimes it is difficult to decide if a model class should use a different model class. It depends on whether the relationship is dense (for example, one contains the other and the contained class will never be used independently). If the two model classes are not strongly related to each other, then the other cannot be controlled; in that case, I would leave work for the third outer class (like a service or just another model class containing the rest).



In your case it DataPeriod

contains dataPoints

(which could be another model class), so I believe it is best to leave the methods there.

+1


source







All Articles