4.4 移除控制标记

【1】原代码

 1 // 重构前
 2 QString foundPerson(QStringList people)
 3 {
 4     QString found = QString();
 5     for (int i = 0; i < people.size(); ++i)
 6     {
 7         if (people[i].compare("Don") == 0)
 8         {
 9             found = "Don";
10         }
11 
12         if (people[i].compare("John") == 0)
13         {
14             found = "John";
15         }
16 
17         if (people[i].compare("Dave") == 0)
18         {
19             found = "Dave";
20         }
21     }
22 
23     return found;
24 }

【2】移除控制标记

 1 // 重构后
 2 QString foundPerson(QStringList people)
 3 {
 4     QStringList candidates = {"Don", "John", "Dave"};
 5     for (int i = 0; i < people.size(); ++i)
 6     {
 7         if (candidates.contains(people[i]))
 8         {
 9             return people[i];
10         }
11     }
12 
13     return QString();
14 }

【3】总结

在一系列布尔表达式中,某个变量带有“控制标记”(control flag)的作用。以break语句或return语句取代控制标记。

 

Good  Good Study, Day Day Up.

顺序 选择 循环 总结

posted @ 2017-08-15 11:50  kaizenly  阅读(502)  评论(0编辑  收藏  举报
打赏