最佳实践返回值VS异常VS枚举 [英] Best Practice Return Value vs Exception vs Enum

查看:225
本文介绍了最佳实践返回值VS异常VS枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出优势和劣势与多个结果值的方法。

I am trying to find out the advantages and disadvantages for a method with multiple result values.

例如我使用一个登录法。如果登录成功,它就会关,否则,我需要知道失败的原因。

For example I'm using a login-method. If the login was successful, it will pass, otherwise I need to know why it failed.

1。返回true或false (没有足够的信息)

bool Login(string user, string password);



2。返回true,如果它是成功的,否则抛出异常

public class UnknownUserException : Exception { }
public class WrongPasswordException : Exception { }
bool Login(string user, string password);



3。返回什么。抛出一个异常,如果没有成功

public class UnknownUserException : Exception { }
public class WrongPasswordException : Exception { }
void Login(string user, string password);



4。返回一个枚举值

enum LoginResult
{
    Successful
    UnknownUser,
    WrongPassword
}
LoginResult Login(string user, string password);



登录就是一个例子情况。我想知道的不同实现的优点和缺点是什么,以及这些情况下,他们都或多或少合适。

"Login" is just one example case. I would like to know what the advantages and disadvantages of the different implementations is, and for which cases they are more or less appropriate.

推荐答案

您会得到更多的自以为是的答案,如果我这样做,我会结合3及4.投掷 LoginFailedException 与枚举说为什么。

You'll get more opinionated answers, If I were doing I'll combine 3 & 4. Throw LoginFailedException with an enum saying why.

void Login(string user, string password);//Or return a bool(redundant though)

class LoginFailedException : ApplicationException
{
    public LoginFailReason Reason {get; private set;}
    public LoginFailedException(LoginFailReason reason)
    {
       this.Reason = reason;
    }
}

enum LoginFailReason
{
    UnknownUser,
    WrongPassword
}

理由选择例外选项:
假设你选择返回值唯一的方法,你的API的用户(可能是客户端或其他开发)可以得到一个机会,忽视了API

Reason to choose exception option: Assume you choose return value only approach, users of your api(may be client, or other developers) can get a chance to overlook the API.

instance.Login(user, password);
var accountInfo = instance.GetAccountInfo();//Assuming logged in; going to explode



谁知道他们必须做这样的

Who knows they have to do like this

if(instance.Login(user, password) == LoginResult.Successful))
{
    var accountInfo = instance.GetAccountInfo();
}



所以,在面对IMO抛出异常说我无法处理您的登录请求由于某某原因。使简单。

So, IMO throw exception in face saying I can't process your login request due to so and so reason. Make it simple.

这篇关于最佳实践返回值VS异常VS枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆