mercredi 5 août 2015

How to validate input in my Person class


public class Person {
private String name;
private String email;
private String password;

public Person(String name, String email, String password) {
    setName(name);
    setEmail(email);
    setPassword(password);
}

public void setName(String name) {
    if (name == null || name.isEmpty()) {
        throw new IllegalArgumentException("Invalid name");
    }

    this.name = name;   
}

public void setEmail(String email) {
    /* Validate email, throw exception */

    this.email = email;
}

public void setPassword(String password) {
    /* Validate password, throw exception */

    this.password = password;
}

}

  1. Best way to validate email adresses, passwords (e.g. 8 characters, at least one upper-case character, one digit, ...) and throw an exception if necessary. The same way I did with name ?

  2. Netbeans complaints about using setters in the constructor ? If I wouldn't and just assign the value directly (this.name = name), I need to validate the input twice (ones's in the cunstroctor and in one's the setter).



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire