-6

I have these long if - else/switch statements, really long, and they make the code hard to read. So was just wondering is there a way to get rid of them? Maybe something like using a class for each condition and then using chain of responsibility pattern ?

What kind of approach would you suggest ?

Here is a sample code:

    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 varified\nPlease contact our support team." );
        errorWindow->show (  );

    }
    else if ....

As you can see, most of the code in the conditional tag is some what similar, except for setting text for errorWindow.

EDIT : It would be nice if people can leave comment on why they down voted.

4

1 回答 1

2

通常,您应该尝试将代码拆分为小的函数/方法,并且每个函数/方法都应该只做一件事。如果你有一个很长(几页)的 if/else 块,你可能应该重构你的代码

我认为代码应该是这样的:

if (shouldIdoThing1()) 
{
  doThingOne(withThis, andThis, andThat);
}
else if (shouldIdoThing2())
{
  doTheSecondThing(withThisOnly);
} 
else
{
  doTheOtherThing(withSomethingElseEntirelyPerhaps);
}

并且,如果可能的话,我会尝试让我的代码看起来像这样。在大型应用程序中,滚动浏览几页只是为了检查所做的事情else是一个真正的痛苦......一个人的头。

于 2013-06-27T09:30:20.540 回答