I have been thinking generally about exception handling.
What would be the best practice for implementing a method that gets a User object based on the supplied username parameter. See below.
/// <summary>
/// Gets a user.
/// </summary>
/// <param name="username">Username</param>
/// <returns>User instance</returns>
public Model.User GetUser(string username)
{
return Context.Users.SingleOrDefault(u => u.Username.ToLower() == username.ToLower());
}
if no user exists with that username parameter, would it be better to return a null User object or rather throw a custom exception specifying that the user does not exist.
Throw an exception. Otherwise, your caller, and your caller’s caller, and everyone else will need to check for
null, or will need to handle an empty collection.If this is a general-purpose method, meant to be used in a context where the caller knows he needs to check for null, then I’d do this a bit differently. I would have a
privatemethod that returns null if there are no users who match. I would add a caller which uses the “try” pattern:and also one that simply returns the user, but throws an exception if not found