Need one design suggestion.
Please see the class below.
Class has just one method
Class has constructor that takes userName and passWord as parameters.
Question is – Whats the difference if
— If i remove the username and pwd from constructor
— And send (userName, password) to the AuthoriseUser method
All this in the background of injecting dependency
public class UserNameAuthorisationService : IUserNameAuthorisationService
{
private readonly string _userName;
private readonly string _password;
private readonly IUserNameAuthorisationRepository _usernameAuthRepository;
public UserNameAuthorisationService(string UserName, string Password, IUserNameAuthorisationRepository UsernameAuthRepository)
{
_userName = UserName;
_password = Password;
_usernameAuthRepository = UsernameAuthRepository;
}
public IUser AuthoriseUser()
{
throw new NotImplementedException();
}
}
Thanks in advance.
Passing initial parameters in constructor is good for non-mutable objects, as if you dont provide setter method it is “impossible” (if not considering any reflection tricks) to change them.
If you plan to not allow this values to change via your API, this is the only way to achieve this requirement. Otherwise you can implement setters. Even implementing setters you may think that this object cant exist (is pointless to exist) without a username and a password, in this case I would keep both setters and constructor initiation.
As I see this object has no meaning to exist without password/username/repository, so I would keep their initialization at constructor.
I would move username and password params to
AuthoriseUsermethod ifUserNameAuthorisationServicewere supposed to act as a component, and have for example, one unique application instance (your DI container should manage this). In this scenario I would inject this object in client objects via DI.The key point is to keep your object at a consistent state all the times, not using init() nor populate() methods. So as @Maxim pointed out, alway fully initialize your objects and keep them always at a usable state, in a way you dont have to throw an exception if
AuthoriseUser()is called without mandatory parameters that were supposed to be pre-populated.