小编Nik*_*ola的帖子

替换嵌套 if 语句的设计模式(箭头反模式)

我注意到我的代码看起来很丑,而且很难维护。基本上我需要对某人进行检查。伪代码是这样的(顺便说一句,我无法在查询中“剪切”任何内容,这并不是我的问题的重点):

List<Person> persons = getPersonsBySomeQuery();

if (checkAnyPersonExists(persons)) {
  if (atLeastOneWithGivenNameExist(persons)) {
    if (noOneWithOtherNameExists(persons)) {
      filteredPersons = filterPersonsWithGivenName(persons);
      if (singleName(filteredPersons)) {
        // single person found
        if (someParameterFromQueryIsTrue) {
          if (someComplicatedLogicIsOK) {
            // found exactly one person, all OK!!!
          } else {
            // found exatcly one person with given name, but not OK
          }
        } else {
           // found exactly one person but parameter from query is not OK
        }
      } else {
        // found only persons with given name, but more …
Run Code Online (Sandbox Code Playgroud)

oop design-patterns if-statement nested chain-of-responsibility

7
推荐指数
1
解决办法
6427
查看次数