项目中大量if...else...优化策略

项目中大量if…else…优化策略

开发中,随着项目逻辑越来越复杂,可能会出现越来越多的if... else...,这样会导致代码的可读性变差,也不利于管理和后来者阅读,所以我们可以采用一些手段来优化代码结构。

下面这是项目中抽出来的部分逻辑,可以看出,随着逻辑的逐渐增多,代码中出现了大量的if...else...

  //do something...
  std::string option;
  std::cin >> option;

  if("gt" == option) {
    // handler `gt`...
  } else if("lt" == option) {
    // handler `lt`...
  } else if ("gte" == option) {
    // handler `gte`...
  } else if ("lte" == option) {
    // handler `lte`...
  } else if ("contains" == option) {
    // handler `contains`...
  } else if ("endswith" == option) {
    //handler `endswith`...
  } else if ("range" == option) {
    //handler `range`...
  } else if ("in" == option) {
    //handler `in`...
  }
  //do something...

我是这样来考虑优化的,将if内的逻辑封装成单独的函数提取出来,然后用std::mapoption的类型和对应函数类型管理起来,这样就降低了main函数中代码的耦合性,后期再加新的逻辑,就非常方便了。后来者管理这段代码也比较方便。

优化后的代码逻辑如下:

//.....
#include <iostream> 
#include <string>
#include <map>
#include <functional> //function

void handler_gt() {
  // handler `gt`... 
}

void handler_lt() {
  // handler `lt`... 
}

void handler_gte() {
  // handler `gte`...
}

void handler_lte() {
  // "handler `lte`..."
}

void handler_contains() {
  // "handler `contains`..."
}

void handler_endswith() {
  // handler `endswith`...
}

void handler_startswith() {
  // handler `startswith`...
}

std::map<std::string, std::function<void (void)>> handler_func_map = {
  {"gt",          handler_gt},
  {"lt",          handler_lt},
  {"gte",         handler_gte},
  {"lte",         handler_lte},
  {"contains",    handler_contains},
  {"endswith",    handler_endswith},
  {"startswith",  handler_startswith},
};

int main() {
  //do something...
  std::string option;
  std::cin >> option;
  
  if (handler_func_map[option]) {
    handler_func_map[option]();
  } else {
    std::cout << "Not support this option" << std::endl;
  }
  //do something...
  return 0;
}


版权声明:本文为zanda_原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。