0

我需要在指定的日期范围或年份范围内从一个或两个不同的数据源向调用者提供记录。

我的困境是我应该使用重载方法还是带有状态验证逻辑的 Request 对象。

所以要么:

public List<Record> getRecords (Date fromDate, Date toDate, boolean dataSourceARequired, boolean dataSourceBRequired)

public List<Record> getRecords (int fromYear, int toYear, boolean dataSourceARequired, boolean dataSourceBRequired)

或类似的东西:

public List<Record> getRecords(Request request)

其中 Request 看起来像:

public class Request{

private final Date fromDate;
private final Date toDate;
private final int fromYear;
private final int toYear;
private final boolean dataSourceARequired;
private final boolean dataSourceBRequired;



public Request(Date fromDate, Date toDate, boolean dataSourceARequired, boolean dataSourceBRequired){

    if (fromDate == null) {
        throw new IllegalArgumentException("fromDate can't be null");
        }
     if (toDate == null) {
        throw new IllegalArgumentException("toDate can't be null");
        }
    if (!dataSourceARequired && !dataSourceBRequired){
        throw new IllegalStateException ("No data source requested");
        }
     if (fromDate.after(toDate)){
         throw new IllegalStateException ("startDate can't be after    endDate");
        }

     this.fromDate = fromDate;
     this.toDate = toDate;
     this.dataSourceARequired = dataSourceARequired;
     this.dataSourceBRequired = dataSourceBRequired;
     this.fromYear = -1;
     this.toYear = -1;

}


 public Request(int fromYear, int toYear, boolean dataSourceARequired, boolean dataSourceBRequired){

    if (fromYear > toYear) {
        throw new IllegalArgumentException("fromYear can't be greater than toYear");
        }
    if (!dataSourceARequired && !dataSourceBRequired){
        throw new IllegalStateException ("No data source requested");
        }

     this.dataSourceARequired = dataSourceARequired;
     this.dataSourceBRequired = dataSourceBRequired;
     this.fromYear = fromYear;
     this.toYear = toYear;
     this.fromDate = null;
     this.toDate = null;

}

}

还是有其他方法?

4

2 回答 2

1

您不应该使用第二种情况,因为它违反了每个类都应该有一个明确定义的责任的规则。在这里,您的班级负责详细的日期范围和年份日期范围。如果你添加更多的标准,这个类会变得很可怕。

所以你可以使用第一种方法,很多人都这样做。

如果您想创建类来封装请求数据,您应该创建一个基本抽象类或接口,然后为您可以使用的每种标准类型创建不同类型的请求子类。例如:

public interface Request {
    execute();
}

public class YearRangeRequest implements Request {
    int fromYear;
    int toYear;

    public execute();

... etc
于 2019-05-16T13:06:05.033 回答
0

另一种解决方案:使用DateRange具有两个构造函数的类:

public class DateRange {
    final Date start;
    final Date end;

    public DateRange(Date start, Date end) {
        this.start = start;
        this.end = end;
    }

    public DateRange(int startYear, int endYear) {
        this(yearBegining(startYear), yearBegining(endYear));
    }

    ...
}
于 2019-05-17T11:38:46.860 回答