我见过每个人都声称嵌套三元结构是一种邪恶,即使在不能用switch编写操作时也是如此;更多的是,我的代码可以很容易地用switch语句编写。
/// <summary>
/// Control sequence character
/// </summary>
private readonly string CSI = "\u001b";
public string ComposeTermSeqs1(TermActions action)
{
switch(action) {
case TermActions.Right:
return CSI + "[C";
case TermActions.Up:
return CSI + "[A";
case TermActions.Left:
return CSI + "[D";
case TermActions.Down:
return CSI + "[B";
case TermActions.ForwardWord: //readline lib
return CSI + "f";
case TermActions.BackWord: //readline lib
return CSI + "b";
case TermActions.BackSearch:
return "\u0012";
case TermActions.Interrupt:
return "\u0003";
default: //TermActions.SuspendApp:
return "\u001a";
}
}但是当我看到函数…的三元版本时
public string ComposeTermSeqs2(TermActions action)
{
return (action == TermActions.Right) ? CSI + "[C"
: (action == TermActions.Up) ? CSI + "[A"
: (action == TermActions.Left) ? CSI + "[D"
: (action == TermActions.Down) ? CSI + "[B"
: (action == TermActions.ForwardWord) ? CSI + "f" //readline lib
: (action == TermActions.BackWord) ? CSI + "b" //readline lib
: (action == TermActions.BackSearch) ? "\u0012"
: (action == TermActions.Interrupt) ? "\u0003"
: "\u001a";
}我不知道,开关大小写是α) (更长的β) )更难维护,因为每次在默认情况下编写一个大小写,而γ)三元版本是纯的,也就是说,当发生错误时,这里没有必要处理这个函数的调试问题,只处理结果。您可能会说第一个版本也是纯的,但是实际上有人可以很容易地为一个案例添加一个附带代码。
我在犹豫…我该选哪一个?
发布于 2015-04-06 17:25:20
我更喜欢开关语句。以下是我的理由:
?、:、==和(),三元版本更难阅读(至少对我来说是如此)。不过,这没什么大不了的。0..N),那么编译器可以使用跳转表将切换简化为: // (伪代码)偏移量= jumpTable索引;https://codereview.stackexchange.com/questions/86011
复制相似问题