我已经读过一个变量永远不应该做多件事.重载变量以执行多个操作是不好的.
因此,我最终编写如下代码:(使用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
}
Run Code Online (Sandbox Code Playgroud)
但在内心深处,我有时想写这样的代码:(没有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
}
Run Code Online (Sandbox Code Playgroud)
这个秘密的欲望会让我成为一个邪恶的程序员吗?
(即第二种情况是非常糟糕的编码习惯吗?)
Har*_*lby 52
我想你误解了这个建议.在这种情况下,您仅将变量用于一个目的 - 存储要搜索的客户.您的逻辑检查是否找到了客户,但未更改变量的用途.
"不要将变量用于多个事物"是针对诸如"临时"变量之类的事情,它们在函数过程中存储十种不同事物的状态.
Bri*_*ndy 10
你问的是并展示了两件不同的东西.
我更喜欢你的第二个代码变体,你有1个变量而不是2个共同依赖.第一段代码可能会有更多问题,因为您有更多的状态可以设法表示同样的事情.
我认为你要问的根本事情是:使用魔术值而不是单独的变量是否可以?这取决于你的情况,但如果你保证魔法值(在这种情况下为null)不能用于表示其他任何东西,那么继续.
当您使用您提供的第一个代码变体时:
如果即使找到对象也可以使用空值,并且您需要区分实际查找客户与否,那么您应该使用2变量变量.
就个人而言,我会考虑将其重构为查找和检查客户的方法,从而大大减少此块长度.就像是:
Customer foundCustomer = null;
if (!this.TryGetLoadedCustomer(out foundCustomer))
foundCustomer = this.FindCustomer();
if (foundCustomer != null)
{ // ...
Run Code Online (Sandbox Code Playgroud)
话虽如此foundCustomer
,在这两种情况下,你都将这个变量用于一个目的.它被用于多个地方,但它用于一个目的 - 跟踪正确的客户.
如果您要使用上面的代码,我个人更喜欢第二种情况而不是您的第一种选择 - 因为在任何情况下都可能需要进行空检查.
在我看来,第二种方式也更好.我会说第一种方法实际上是错误的,因为你有两个相互依赖的变量,并为你提供冗余信息.这将打开他们是不一致的可能性-你可以犯了一个错误,并有customerFound
可以true
,但foundCustomer
要null
.在那种情况下你是做什么的?这个州最好不可能达到.