Question

I'm developing an C# library with .NET Framework 4.0.

I have a method that has to return an object and the result of that operation. In my case it is a login method, I use as argument user name and password, and I have to return an instance of User class and the result of the login operation:

  • Invalid user name or password.
  • User locked.
  • User disabled.
  • Etc.

I thought, I can do it this way:

public LoginResult DoLogin(string userName, string password, out User user)

Is that correct? Is there another way to do it? Maybe I can use an exception instead of return a LoginResult value.

Was it helpful?

Solution 2

What you describe is an appropriate way if there is no further information assigned with the states such as user locked or user disabled.

If there is, I'd like to suggest an alternative model:

Create an abstract class LoginResultInfo that has an abstract read-only property of type LoginResult that will return the "error code".

From that class, you can then derive a subclass for each of the desired error codes. Each of these subclasses overrides the LoginResult property to return the appropriate error code, and each contains the relevant additional fields, such as a User instance in the case of a successful login, a text originally supplied by an admin explaining why a user was locked, or the timestamp of when a user disabled their account etc.

With the LoginResult property, you still have a way to conveniently switch over the different error codes, while at the same time, you don't supply any fields that are used only sometimes, but instead you have a class structure specific and suitable to the situation at hand.

OTHER TIPS

This seems to be an appropriate way, as some framework functionls like TryParse do it exactly this way.

I would recommend to make LoginResult a property of User class and return the User class object from your DoLogin method instead of returning it as on output parameter. You can always fill the LoginResult property while filling your User object as the purpose of having a User class means the user instance is either authenticated or unauthenticated by the value of LoginResult

public User DoLogin(string userName, string password){}

public class User
{
    public LoginResult UserLoginResult {get; set;} 

    // Other properties.....
}

The method you suggested is the most appropriate one according to your requirement.
One more point I will like to highlight,

  1. It is not a good practice to decide the flow of the program by throwing exceptions.

The other ideas that pops up in my mind are,

  1. Generate a class having both the properties and return that object
  2. Return a KeyValuePair<LoginResult, User > object

You can use

Tuple<User, LoginResult>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top