Can Data Classes Contain Methods for Validation?

datavalidation

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?

Best Answer

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.

Related Topic