去掉if-else并在c++中切换

Getting rid of if-else and switch in c++

本文关键字:c++ if-else 并在 去掉      更新时间:2023-10-16

我有这些很长的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中做了什么,这在。。。一个人的头。