【问题标题】:Design pattern for related nested conditionals相关嵌套条件的设计模式
【发布时间】:2023-01-07 02:42:07
【问题描述】:

我知道大多数条件地狱都可以通过使用策略、命令、责任链等设计模式以更面向对象的方式进行简化。

不包含许多侧分支(同一级别的分支)但嵌套很深并且每个条件都取决于前一个条件的结果的条件呢?

这是一个例子:

nestedFunction(input: Input){
    if(input!=null){
      a = func1(input)
      if(p(a)){    // where p() is a predicate
         b = func2(a)
         if(p(b)){
           c = func3(b)
           if(p(c)){
              // dosomething1
           } else {
             // dosomething2
          }
         } else {
           // dosomething3
         }
      } else {
         // dosomething4
      }
    } else {
     // dosomething5
    }      
}

我可以通过将每个嵌套的嵌套条件提取到不同的函数中来简化它,如下所述:https://blog.codinghorror.com/flattening-arrow-code/

但我很好奇是否有更面向对象的友好方式来做到这一点?

【问题讨论】:

    标签: design-patterns


    【解决方案1】:

    您可以使用 Pipeline Pattern

    管道具有一系列链接在一​​起的 IO 步骤,下一步将处理上一步的输出。您可以使用分支步骤处理条件语句,这些步骤只进行委托而不是实际处理。

    例如(不幸的是 JS 不是类型安全的,但你明白了) 显然这个例子有点愚蠢和过度设计,因为标准函数组合会更简单和优雅......

    const pipeline = ifNotNull(
      input => pipe(
        input => input.toUpperCase(),
        input => input + " added suffix",
        console.log
      )(input), 
      () => console.log('input was null')
    );
    
    
    pipeline(null);
    pipeline("some value");
    
    
    function ifNotNull(thenStep, elseStep) {
      return match({
        condition: input => input !== null,
        body: thenStep
      }, {
        condition: () => true,
        body: elseStep
      });
    }
    
    function match(...branches) {
      return input => {
        for (branch of branches) {
          if (branch.condition(input)) {
            return branch.body(input);
          }
        }
      };
    }
    
    function pipe(...steps) {
      return input => {
        for (step of steps) {
          input = step(input);
        }
        
        return input;
      };
    }

    【讨论】:

      猜你喜欢
      • 2010-09-07
      • 1970-01-01
      • 2020-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多