java - 如何进行不同类型的对象状态验证

标签 java validation design-patterns object-state

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

我的困境是我应该使用重载方法还是具有状态验证逻辑的 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)

请求看起来像这样:

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;

}

}

或者还有其他方法吗?

最佳答案

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

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

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

public interface Request {
    execute();
}

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

    public execute();

... etc

关于java - 如何进行不同类型的对象状态验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56169123/

相关文章:

java - While 循环跑掉

java - 反转 Collectors.toMap 以添加到 ArrayList

forms - 给定 GraphQL 模式,是否可以进行客户端预突变验证?

objective-c - 对 Objective-c View 、代表和导出的混淆

java - Java API 设计中的面向对象事件日志记录

java - OSGI 声明式服务 (DS) : What is a good way of using service component instances

java - 如何从 pom.xml 获取属性值?

Java泛型通配符运算符

c++ - 在 C++ 中验证一个字符串是否只包含字母

php - 具有不同设计的两个数据库之间的映射