gpt4 book ai didi

c# - 检查 'success' 是否为 null 算作 "Double use of variables"?

转载 作者:IT王子 更新时间:2023-10-29 04:31:52 25 4
gpt4 key购买 nike

我读到一个变量永远不应该做超过一件事。重载一个变量来做不止一件事是不好的。

因此,我最终编写了如下代码:(使用 customerFound 变量)

bool customerFound = false;
Customer foundCustomer = null;
if (currentCustomer.IsLoaded)
{
if (customerIDToFind = currentCustomer.ID)
{
foundCustomer = currentCustomer;
customerFound = true;
}
}
else
{
foreach (Customer customer in allCustomers)
{
if (customerIDToFind = customer.ID)
{
foundCustomer = customer;
customerFound = true;
}
}
}
if (customerFound)
{
// Do something
}

但内心深处,有时我想这样写我的代码:(没有 customerFound 变量)

Customer foundCustomer = null;
if (currentCustomer.IsLoaded)
{
if (customerIDToFind = currentCustomer.ID)
{
foundCustomer = currentCustomer;
}
}
else
{
foreach (Customer customer in allCustomers)
{
if (customerIDToFind = customer.ID)
{
foundCustomer = customer;
}
}
}
if (foundCustomer != null)
{
// Do something
}

这种 secret 欲望会让我成为邪恶的程序员吗?

(即第二种情况真的是糟糕的编码实践吗?)

最佳答案

我认为您误解了建议。在这种情况下,您仅将变量用于一个目的 - 存储正在搜索的客户。您的逻辑会检查是否找到了客户,但不会更改变量的用途。

“不要为超过一件事使用变量”针对的是像“临时”变量这样的东西,它在一个函数的过程中为十个不同的东西存储状态。

关于c# - 检查 'success' 是否为 null 算作 "Double use of variables"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2992459/

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