I have the following piece of code in my DataModel.cs class:
public User ValidateUser(string Username, string Password)
{
DataContext db = new DataContext();
var query = from u in db.Users where (u.Username == Username && u.Password == Password) select u;
if (query.Count() != 0)
{
return query.First();
}
else
{
return new User { UserID = -1 };
}
}
I have a login class calling this on my DataModel, checking to see if a user is valid. If the user is valid than I want to have a reference to that “logged-in” user in my login class (which is why ValidateUser returns a user object).
Right now, if that user doesn’t exist or the password is wrong, I simply return an empty User object with the id set to -1 to flag it as being not a real user.
Is this bad practice?
How should I handle this case? If ValidateUser just returned a bool it wouldn’t be a problem but because I also need a reference to that user I don’t know how else to do it.
IMO, this is bad practice, because it is implicit. If nothing is returned, the method should return null. This is self-explanatory.
Or, if it needs to be handled completely different as the normal case or needs additional information, you could consider to throw an exception.