去掉if-else并在c++中切换
Getting rid of if-else and switch in c++
我有这些很长的if-else/switch语句,非常长,它们使代码难以阅读。所以我只是想知道有没有办法摆脱他们?也许类似于为每个条件使用一个类,然后使用责任链模式?
你建议采取哪种方法?
这是一个示例代码:
if ( cc == LIB_DEFINED_CONSTANT_1 )
{
response = "-1";
errorWindow->setText ( "The operation timed out.nPlease try again later." );
errorWindow->show ( );
}
else if ( cc == LIB_DEFINED_CONSTANT_2 )
{
response = "-1";
errorWindow->setText ( "Couldn't conect to the server.nPlease try again later." );
errorWindow->show ( );
}
else if ( cc == LIB_DEFINED_CONSTANT_3 )
{
response = "-1";
errorWindow->setText ( "Access is denied.nPlease contact our support team." );
errorWindow->show ( );
}
else if ( cc == LIB_DEFINED_CONSTANT_4 )
{
response = "-1";
errorWindow->setText ( "Credentials and varifiednPlease contact our support team." );
errorWindow->show ( );
}
else if ....
正如您所看到的,除了为errorWindow设置文本之外,条件标记中的大多数代码都是类似的。
编辑:如果人们能评论他们为什么投了反对票,那就太好了
通常,您应该尝试将代码拆分为小函数/方法,每个函数/方法应该只做一件事。如果您有一个很长(几页)的If/else块,您可能应该重构代码。
我认为代码应该读成这样:
if (shouldIdoThing1())
{
doThingOne(withThis, andThis, andThat);
}
else if (shouldIdoThing2())
{
doTheSecondThing(withThisOnly);
}
else
{
doTheOtherThing(withSomethingElseEntirelyPerhaps);
}
如果可能的话,我试着让我的代码看起来像那样。在大型应用程序中,滚动几个页面只是为了检查else
中做了什么,这在。。。一个人的头。
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 如何删除peer if else分支中的冗长句子
- 我似乎对if/else的基本语句有问题:/
- 使用if-else将数字转换为单词
- 为什么这个案例陈述需要一个"if else"而不仅仅是一个"if"?
- C++ If/Else 语句被跳过
- 如果条件不相关,我应该更喜欢两个 if 语句而不是 if-else 语句吗?
- 如何将 if else 语句重写为 switch 语句
- 在 C++ 中的 if-else if- else 语句期间更改变量
- 为什么我的 if else 语句不起作用并从数组中输出正确的索引?
- 我的 If Else 语句无法在向量 (C++) 中提供最大值
- 具有嵌套 if-else 的循环的时间复杂度
- 为什么无论输入如何,所有 if-else 语句都会打印?
- 简化对两个布尔值的 4 个 if/else 检查
- 如何在C++中创建 if else 循环而不是多个嵌套?
- 为什么切换 if else 语句的顺序会导致错误?
- 如何使用 if else 语句
- if/else 语句输出由于加号或减号而未显示正确的消息
- 如何解释 #if/#else 位域?(VC++菜鸟)
- if-else 语句仅按特定顺序工作,我不知道为什么