Skip to main content
edited tags; edited tags
Link
Christophe
  • 82.3k
  • 11
  • 136
  • 202
Source Link
kibe
  • 738
  • 1
  • 7
  • 12

Can I put domain services inside domain entities?

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:

  1. 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 } } } 
  1. 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.