Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods that return meaningful return values

Tags:

c#

I work in C#, so I've posted this under C# although this may be a question that can be answered in any programming language.

Sometimes I will create a method that will do something such as log a user into a website. Often times I return a boolean from the method, but this often causes problems because a boolean return value doesn't convey any context. If an error occurs whilst logging the user in I have no way of knowing what caused the error.

Here is an example of a method that I currently use, but would like to change so that it returns more than just 0 or 1.

public bool LoginToTwitter(String username, String password)
{
    // Some code to log the user in
}

The above method can only return True or False. This works well because I can just call the following:

if(http.LoginToTwitter(username, password))
{
    // Logged in
} else {
    // Not Logged in
}

But the problem is I have no way of knowing why the user wasn't logged in. A number of reasons could exist such as: wrong username/password combination, suspended account, account requires users attention etc. But using the following method, and logic, it isn't possible to know this.

What alternative approaches do I have?

like image 606
James Jeffery Avatar asked Jul 21 '13 19:07

James Jeffery


2 Answers

You could create and return an enum with expected LoginResults.

public enum LoginResult
{
   Success,
   AccountSuspended,
   WrongUsername,
   WrongPassword,
}

Then return using the enum type in your method:

public LoginResult LoginToTwitter(String username, String password)
{
    // Some code to log the user in
}
like image 99
Dan Teesdale Avatar answered Oct 18 '22 12:10

Dan Teesdale


You could choose to either throw an exception with a relevant message attached (and have the calling method deal with the exception), or have the function return an enum with different states (such as LoginState.Success, LoginState.IncorrectPassword, etc.).

If you are using exceptions, it's probably best to have your function return nothing (public void LoginToTwitter), but if you're using an enum, make sure the set the return type to the name of your enum (public LoginState LoginToTwitter).

like image 23
kevinji Avatar answered Oct 18 '22 14:10

kevinji