OK, say I have a data class for a user:
public class User {
private String firstName;
private String lastName;
private long personCode;
private Date birthDate;
private Gender gender;
private String email;
private String password;
Now let’s say I want to validate email, whether names are not empty, whether birth date is in normal range, etc. Can I put that validation method in this class together with data? Or should it be in UserManager which in my case handles the lists of these users?
8
You can definitely validate these attributes in your setters(). Unlike getters which are meant to return values, setters are methods to assign a value via an argument/parameter.
Ideally, i would advise you to write separate methods and have their return values true or false. for validating your class attributes particularly when the validation is quite extensive.
Examples:
bool validateEmail(string email) {
}
bool validatePassword(string pwd) {
}
bool validateBirthdate(date dob) {
}
I would rather advise to validate your class attributes in the Business Logic Layer. I wonder if you know about the software logical architecture. FYI: BLL
Also if you have a database then it is best to have them validated there via constraints.
Don’t put the code that actually does the validation logic in with the class itself – see SRP principle. And what if you were to code some validation for something that might be useful to another class (for example email validation)? Extract each type of validation logic out to its own separate class.
If you are coding in Java, you should take a look at Bean Validation, that is part of the Java EE 6 specification. It uses metadata (annotations) to help validation handling. Bean validation can also be used in other layers.
Hope it helps you.
In short, YES you can definitely implement that validation method on a class.
I would also advice to define validation method (or methods) through a common interface like IValidate. It will look somewhat like:
public class User: IValidate
{}
You may define the generic public bool IsValid()
method signature and others that make sense in the given context.
1