我有一堂课:时间表。
public class Schedule {
private int locationNum;
private int cost;
private String costReason;
private Date weekOfChange;
private Date dayOfChange;
private String changeReason;
// and all those getters and setters
public Schedule(int locationNum, int cost, String costReason, Date weekOfChange, Date dayOfChange, String changeReason) throws ApplicationException {
//change is all or nothing - all attributes are present or none
if((weekOfChange!=null && dayOfChange!=null && changeReason!=null) || (weekOfChange==null && dayOfChange == null && changeReason == null)) {
this.weekOfChange = weekOfChange;
this.dayOfChange = dayOfChange;
this.changeReason = changeReason;
}
else { throw new ApplicationException();}
//similary another if block to ensure that if cost is specified
//then there exists the corresponding reason code for it.
}
}
到目前为止,我喜欢我的 Schedule 课程。但是,我还没有完成检查,我将不得不做一些其他检查:
- locationNum 是数据库中的有效商店编号。
- 是数据库中这 6 个不同的 changeReason 代码之一的 changeReason 文本。
- 等等等等……
通常,我不会在 Schedule 类中编写这些,因为很明显,我不能从此类中调用 DAO。因此,我将有一个业务层和某种验证器类,接受一个 Schedule 类型的对象并按顺序执行一堆数据库验证并收集错误以进行显示/其他。
现在,这是我的问题:
- 如果您将 Schedule 视为 POJO 并争辩说对象不负责验证自身 - 我将不得不将构造函数中的所有代码移动到业务层的验证器类。但是,如果我要这样做,难道不是日程安排乏力吗?这就是他们所说的违反单一责任原则吗?
- 假设我将构造函数中的代码移到业务层类中,以便现在所有类型的验证都在我的业务层中。假设有人在我的数据存储中将 dayOfChange 更改为 NULL,现在我正在从我的数据库中加载对象。现在,有了这种对象,我的应用程序可能会崩溃,不是吗?因为假设满足验证规则,我会编写代码。我想我的问题越来越令人困惑,但我想说的是,在这种情况下,我宁愿在构造函数中完成这些检查,以确保 Schedule 类隐藏的数据的完整性。
- 一般是怎么做的?最佳做法是什么?
感谢您参与本次讨论。