gpt4 book ai didi

c# - 方法应该处理空值吗?在这种情况下的最佳实践?

转载 作者:行者123 更新时间:2023-11-30 14:48:52 26 4
gpt4 key购买 nike

我在代码中有以下情况,最好的管理方式是什么,评论中包含这些情况,请推荐最佳做法。

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;
}

最佳答案

首先是构造

catch (Exception e) {
throw;
}

多余的,可以消除。现在关于null。有两个案例:

  • 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);

关于c# - 方法应该处理空值吗?在这种情况下的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40106136/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com