我在我正在处理的代码库中遇到了一个 switch 语句,我正在尝试找出如何用更好的东西替换它switch 语句被认为是代码味道 http://c2.com/cgi/wiki?SwitchStatementsSmell。然而,读完后several https://stackoverflow.com/questions/126409/ways-to-eliminate-switch-in-codestackoverflow 上的帖子关于替换 https://stackoverflow.com/questions/374239/why-doesnt-python-have-a-switch-statement#374290 switch https://stackoverflow.com/questions/561401/refactor-my-c-code-switch-statement 声明 https://stackoverflow.com/questions/338206/switch-statement-with-strings-in-java我似乎想不出一种有效的方法来替换这个特定的 switch 语句。
这让我想知道这个特定的 switch 语句是否可以,以及是否有特定情况下 switch 语句被认为是合适的。
就我而言,我正在努力解决的代码(自然有点混乱)是这样的:
private MyType DoSomething(IDataRecord reader)
{
var p = new MyType
{
Id = (int)reader[idIndex],
Name = (string)reader[nameIndex]
}
switch ((string) reader[discountTypeIndex])
{
case "A":
p.DiscountType = DiscountType.Discountable;
break;
case "B":
p.DiscountType = DiscountType.Loss;
break;
case "O":
p.DiscountType = DiscountType.Other;
break;
}
return p;
}
谁能建议一种方法来消除这个开关?或者这是开关的适当使用吗?如果是的话,switch 语句还有其他合适的用途吗?我真的很想知道它们在哪里合适,这样我就不会浪费太多时间试图消除我遇到的每个 switch 语句,因为它们在某些情况下被认为是一种气味。
Update:在建议下Michael https://stackoverflow.com/questions/1071856/when-should-one-try-to-eliminate-a-switch-statement/1071879#1071879我做了一些搜索这个逻辑的重复,发现有人在另一个类中创建了逻辑,这实际上使整个 switch 语句变得冗余。因此,在这段特定代码的上下文中,switch 语句是不必要的。然而,我的问题更多是关于代码中 switch 语句的适当性,以及我们是否应该在发现它们时始终尝试替换它们,因此在这种情况下,我倾向于接受此 switch 语句是适当的答案。
这是 switch 语句的适当用途,因为它使选项可读,并且易于添加或减去选项。
请参阅此链接。 https://stackoverflow.com/questions/449273/why-the-switch-statement-and-not-if-else
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)