【问题标题】:How to refactor "if x return x" statements如何重构“if x return x”语句
【发布时间】:2021-06-01 17:33:02
【问题描述】:

我正在寻找一种方法来重构这种“如果 x 返回 x”模式。好像是多余的。

例如:

async exampleFunction(a) {
    const firstResult = await this.firstHandler(a);

    if (firstResult) {
        return firstResult;
    }

    const secondResult = await this.secondHandler(a);

    if (secondResult ) {
        return secondResult;
    }

    const thirdResult = await this.thirdHandler(a);

    if (thirdResult) {
        return thirdResult;
    }
}

【问题讨论】:

  • 这很好 IMO,因为您希望该方法在收到 firstResult 后立即停止。
  • 更少的代码不等于更好的代码。你所拥有的东西很容易阅读,而且很有意义。除非你是故意打代码高尔夫,否则我认为这很好。
  • 我不是在打代码高尔夫,但我有很多使用这种模式的函数调用
  • 你可以做const res=await a() || await b(); return res;
  • 是的,就是这样或工作方式

标签: javascript refactoring


【解决方案1】:

function exampleFunction(a) {
    return this.firstHandler(a) || this.secondHandler(a);
}

【讨论】:

    猜你喜欢
    • 2016-07-07
    • 2014-10-07
    • 2017-02-05
    • 2012-06-03
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多