Created
May 9, 2016 20:19
-
-
Save nikkatsa/212274d56bef287d74138fb48dc4ec7b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class PersonBuilder { | |
private static final Pattern EMAIL_VALIDATION_REGEX = Pattern.compile("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"); | |
private String name; | |
private String surname; | |
private int age; | |
private String email; | |
private PersonBuilder() { | |
} | |
public final PersonBuilder withName(final String name) { | |
this.name = name; | |
return this; | |
} | |
public final PersonBuilder withSurname(final String surname) { | |
this.surname = surname; | |
return this; | |
} | |
public final PersonBuilder withAge(final int age) { | |
this.age = age; | |
return this; | |
} | |
public final PersonBuilder withEmail(final String email) { | |
this.email = email; | |
return this; | |
} | |
public final Person build() { | |
this.validate(); | |
return new Person(this.name, this.surname, this.age, this.email); | |
} | |
private void validate() { | |
Objects.requireNonNull(this.name, "The person should have a name"); | |
Objects.requireNonNull(this.surname, "The person should have a surname"); | |
Objects.requireNonNull(this.email, "The person should have an email"); | |
if (this.age <= 0) { | |
throw new IllegalArgumentException(String.format("Age should be a positive integer")); | |
} | |
if (!EMAIL_VALIDATION_REGEX.matcher(this.email).matches()) { | |
throw new IllegalArgumentException("Invalid email"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment