DDD-NoDuplicates icon indicating copy to clipboard operation
DDD-NoDuplicates copied to clipboard

Passing the number of users with a similar name to the constructor.

Open lncendia opened this issue 2 years ago • 2 comments

If you receive in the constructor of the User class the number of users with the same email as the int variable. In the constructor, check if it is greater than 1, then throw an exception. In the repository, define a method to get the number of suitable records. What do you think about this?

lncendia avatar Dec 05 '22 11:12 lncendia

I'm not sure I like the idea of an int parameter on a constructor that is simply a calculated field and isn't used in the object itself. You could just as well pass in a bool duplicateEmailExists and only create the instance if it's false (and this would be more clear, IMO, than the int option). If you wanted to do something in the constructor like this, I would probably pass in a Func<bool, string> or Func<bool, EmailAddress> (if you have a value object for EmailAddress) into the constructor, along with the emailAddress, and then make the call inside the constructor, like this:

public User(string emailAddress, Func<bool,string> emailExists)
{
  if(emailExists(emailAddress)) throw Exception();
  // assign fields
}

This makes it more apparent that one should be performing a check, not just passing in a magic value. Of course if the Func needs to be async, this can be problematic in a constructor. Without actually coding it I'm not sure if that's a show-stopper to this approach or not, but it could certainly be an issue.

ardalis avatar Dec 07 '22 18:12 ardalis

Thank you so much for the answer! In this case, I am most impressed with method 3 (passing all the necessary data to the constructor). But then I have a question. For example, I have a User aggregate and a Link aggregate (in this context, it means a connection with another User, such as a friend request in a social network, can be confirmed and not confirmed). I need a user who has more than 20 confirmed connections not to be able to create new ones. Should I pass all Link aggregates to the constructor, Link aggregates of a specific user, or confirmed Link aggregates of a specific user to the Link aggregate constructor?

lncendia avatar Dec 07 '22 18:12 lncendia