方法应该处理空值吗?这种情况下的最佳做法是什么?

时间:2016-10-18 10:46:37

标签: c# parameters null

我在代码中有以下情况,最好的方法是管理它,评论包含情况,请推荐最佳实践。

try
{
    string errorMessage = AccountClient.GetAccount(id, out accountDetails);

    // FIRST WAY : REMOVE THIS NULL CHECK AT ALL AND LEAVE GetAccountDetails to control
    // the Null situation?
    if (accountDetails == null)
    {
        // Second Way: This way? Throw exception here?
        throw new ArgumentNullException(nameof(accountDetails));
        //Third way? break the function?
        break;
    }

    // GetAccount Details already has null control
    Subscription subscription = AccountProcessor.GetAccountDetails(accountDetails);
}
catch (Exception e)
{
    throw;
}

3 个答案:

答案 0 :(得分:3)

首先,构建

catch (Exception e) {
  throw; 
}

冗余,可以消除。现在大约null s。有两个 例:

  • null错误的值,因此应该发出信号
  • null预期的普通值,因此应该继续

所以你有(null是错误的)

string errorMessage = AccountClient.GetAccount(id, out accountDetails);

// What's wrong: it's id which doesn't correspond to any detail 
// (we expect id being s.t. AccountClient.GetAccount(id...) returns not null detail)
if (accountDetails == null) 
  throw new ArgumentException($"Incorrect id {id} which doesn't have any detail.", 
                              nameof(id));

Subscription subscription = AccountProcessor.GetAccountDetails(accountDetails);

或(null是预期结果)

string errorMessage = AccountClient.GetAccount(id, out accountDetails);

if (accountDetails == null)
  return null; // or any reasonable value, or just return, or create new Subscription

Subscription subscription = AccountProcessor.GetAccountDetails(accountDetails);

答案 1 :(得分:1)

如果你可以对空输入做任何事情,那就处理它。

try
{
    string errorMessage = AccountClient.GetAccount(id, out accountDetails);

    if (accountDetails == null)
    {
         // do something about it. Maybe write some logs, substitute with a default value
         // or throw appropriate exception ...
    }

    Subscription subscription = AccountProcessor.GetAccountDetails(accountDetails);
}
catch (Exception e)
{
    throw;
}

如果你不能让GetAccountDetails决定应该发生什么。

try
{
    string errorMessage = AccountClient.GetAccount(id, out accountDetails);
    Subscription subscription = AccountProcessor.GetAccountDetails(accountDetails);
}
catch (Exception e)
{
    throw;
}

此外,无需捕获异常,不执行任何操作,然后throw,以便您可以删除整个try catch块。

答案 2 :(得分:1)

这取决于此ID的来源。如果用户键入了ID,那么我就不会生成异常,因为它不是程序中的错误。只需处理用户输入并显示正确的消息即可。例外是昂贵的,所以我通常只在我有一个真正的程序失败时才使用它们。除此之外,如果你编写一个自定义的异常处理程序,记录由错误的用户输入引起的错误是没有意义的。所以我会这样做:

if (AccountClient.AccountExists(id))
{
    AccountDetails details = AccountClient.GetAccount(id);
    Subscription subscription = AccountProcessor.GetAccountDetails(accountDetails);
}

无论如何,以同样的方式处理输入是好的,即使你已经像上面那样对待,以防有任何其他未经处理的呼叫:

public AccountDetails GetAccount(int id)
{
    if (Exists(id))
        GetTheAccount(id);
    else
        throw new Exception(String.Format("Account {0} doesn't exists", id));
}

在这种情况下,我会使用Exception,因为例如,如果调用者函数传递了错误的值,它可能真的表示错误。