Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
lncendia opened this issue Dec 5, 2022 · 2 comments
Open

Comments

@lncendia
Copy link

lncendia commented Dec 5, 2022

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?

@ardalis
Copy link
Owner

ardalis commented Dec 7, 2022

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.

@lncendia
Copy link
Author

lncendia commented Dec 7, 2022

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants