Say I have a domain entity User:
class User {
constructor (username, email, password) {
this.username = username
this.email = email
this.password = password
}
}
Now, all users need a way to validate their username and email
There are two ways I can think of doing so:
- Inside the domain entity (
domain/entities/User.js
)
class User {
constructor (username, email, password) {
this.username = username
this.email = email
this.password = password
}
validate () {
// validation logic
// ...
if (!this.username.isValid || !this.email.isValid) {
return false
} else {
return true
}
}
}
- In a domain service (
/domain/services/validateUser.js
)
function validateUser (userToValidate) {
// validation logic
// ..
if (userIsValid) {
return true
} else {
return false
}
}
Either way, the use case/application service calls the validation logic
function createUserUseCase (username, email, password) {
const user = new User(username, email, password)
const isValid = user.validate()
// ...
// or... calling a service
const user = new User(username, email, password)
const isValid = validateUser(user)
}
So, should entities also carry logic or only hold data? Can I put validation logic inside an Entity, or do I have to create a service that receives a user and validates the user?
Thanks.