Last active
January 18, 2022 10:51
-
-
Save emilybache/1091615234afd1e1f2da37ccf7046964 to your computer and use it in GitHub Desktop.
Peel with a domain event instead of a boolean
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
record EmailChangedMessage(int userId, String newEmail) implements DomainEvent {} |
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 void changeEmail(String newEmail) | |
{ | |
var emailChangedMessages = changeEmailInDatabase(newEmail); | |
for (EmailChangedMessage message : emailChangedMessages) { | |
MessageBus.sendEmailChangedMessage(message.userId(), message.newEmail()); | |
} | |
} | |
List<EmailChangedMessage> changeEmailInDatabase(String newEmail) { | |
Object[] data = Database.getUserById(userId); | |
email = (String)data[1]; | |
userType = (UserType)data[2]; | |
if (Objects.equals(email, newEmail)) | |
return Collections.emptyList(); | |
Object[] companyData = Database.getCompany(userId); | |
int companyId = (int)companyData[0]; | |
String companyDomainName = (String)companyData[1]; | |
int numberOfEmployees = (int)companyData[2]; | |
String emailDomain = newEmail.split("@")[1]; | |
boolean isEmailCorporate = Objects.equals(emailDomain, companyDomainName); | |
UserType newType = isEmailCorporate | |
? UserType.Employee | |
: UserType.Customer; | |
if (userType != newType) | |
{ | |
int delta = newType == UserType.Employee ? 1 : -1; | |
int newNumber = numberOfEmployees + delta; | |
Database.saveCompany(companyId, companyDomainName, newNumber); | |
} | |
email = newEmail; | |
userType = newType; | |
Database.saveUser(this); | |
EmailChangedMessage message = new EmailChangedMessage(this.userId, newEmail); | |
return List.of(message); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment