I have a class : Schedule.
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.
}
}
So far, I am liking my Schedule class. However, I am not done with the checks, I would have to do some other checks:
- is the locationNum a valid store number in the database.
- is changeReason text one of those 6 different changeReason codes in the database.
- etc etc....
Typically, I would not write these in Schedule class, coz obviously, I cannot invoke DAOs from this class. So, I would have a business layer and some kind of validator class, accepting an object of type Schedule and performing a bunch of database validations in sequence and collecting errors for display / whatever.
Now, here are my questions:
- If you were to treat Schedule as a POJO and argue that an object is not responsible for validating itself - I would have to move all of the code in the constructor to the business layer's validator class. But, if I were to do this, isn't Schedule anemic? Is this what they call violation of Single Responsibility principle?
- Lets presume I moved the code I have in my constructor to a business layer class so that all kinds of validations are now in my busines layer. Lets assume that someone changes dayOfChange to NULL in my datastore and now I am loading objects from my database. Now, with this kind of an object, my application can break, wouldn't it? coz I would have written code assuming that validation rules are met. I guess my question is getting confusing, but the point I am trying to make is that in this context I would rather have these checks done in constructor to ensure integrity of the data hidden by Schedule class.
- How is it done usually? What is the best practice?
Appreciate your involvement in this discussion.