Patrón Value-Object

public final class UserRegisterer {    // Dependencies and constructor    public void register(String email) {
if (!isValid(email)) {
throw new InvalidEmail();
}
User user = new User(email);
repository.save(user);
}
private boolean isValid(String email) {
// Some email validation implementation
}
}
public final class User {
private int id;
private String email;
public User(email) {
setEmail(email);
}
public void setEmail(String email) {
if (!isValid(email)) {
throw new InvalidEmail();
}
this.email = email;
}
private boolean isValid(String email) {
// Some email validation implementation
}
}
public final class ContactCreator {    // Dependencies and constructor    public void addContact(String email, int userId) {
User user = userRepository.findById(userId);
// We need to validate the email!

Contact contact = new Contact(email, user)
contactRepository.save(contact);
}
}
user.isValid(email) // Don't do this!!
public final class EmailAddress {
private final String value;
public EmailAddress(String value) {
if (!isValid(email)) {
throw new InvalidEmail();
}
this.value = value;
}
private boolean isValid(String value) {
// Some email validation implementation
}
}
public final class Address {
private final String streetName;
private final int streetNumber;
// Constructor, etc.
}
public final class Contact {
private int id;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
private String streetName;
private int streetNumber;
private String city;
private String zipCode;
private String country;
public Contact(
String firstName,
String lastName,
String email,
String phoneNumber,
String streetName,
int streetNumber,
String city,
String zipCode,
String country) {
// ...
}
}
public final class Contact {
private ContactId id;
private Name name;
private EmailAddress email;
private PhoneNumber phoneNumber;
private Address address;
public Contact(
ContactId id,
Name name,
EmailAddress email,
PhoneNumber phoneNumber,
Address address) {
this.id = id;
this.name = name;
this.email = email;
this.phoneNumber = phoneNumber;
this.address = address;
}
}

--

--

We are the team that thinks, works and aims to ensure you a successful digital journey. 👨🏻‍💻👩🏻‍💻 #webdevelopment #digital #technology

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Lambdaloopers

Lambdaloopers

We are the team that thinks, works and aims to ensure you a successful digital journey. 👨🏻‍💻👩🏻‍💻 #webdevelopment #digital #technology