Coder Social home page Coder Social logo

Comments (4)

lcxfs1991 avatar lcxfs1991 commented on May 9, 2024

这条可能考虑禁止,将代码扁平化。

from eslint-config-alloy.

xcatliu avatar xcatliu commented on May 9, 2024

禁用这个规则有以下几个原因:

1. 我觉得下面两种写法中,前者阅读起来更清晰:

// 阅读起来结构清晰,层次分明,在同一个缩进层次下
function foo() {
    if (bar) {
        return doSomething();
    } else {
        return doOther();
    }
}
// 没有前者结构清晰,特别是代码行数较多的时候
function foo() {
    if (bar) {
         return doSomething();
    }
    return doOther();
}

2. early return 写多了之后,容易舍本逐末的想给每个 if 都加个 return,即使它根本不需要返回值

// 正常写法,不需要返回值
function foo() {
    if (bar) {
        doSomething();
    } else {
        doOther();
    }
}
// 为了 early return,而使 foo 有了返回值
function foo() {
    if (bar) {
        return doSomething();
    }
    doOther();
}

from eslint-config-alloy.

mengjian-github avatar mengjian-github commented on May 9, 2024

@xcatliu 这确实是一个有争议性的话题,强制开启可以让代码更加扁平化,依靠层次结构来表现清晰带来的好处可能抵不过else return所带来的可能层级嵌套很深带来的副作用。

前端的一个很重要的话题就是消除回调地狱,这条规则可以很有效的避免层级过深的情况,如果大家都遵循规范,我们将习惯于阅读扁平化的代码,清晰度不会比简单的缩进带来的清晰度差很多。

一般情况下early return用于处理一些异常情况,见过有人在if return后在else里面又进行异步调用,异步调用中再来个if else,这个时候如果能开启该规则,可以避免陷入回调地狱,我看到这样的代码会感到十分不舒服。

from eslint-config-alloy.

xcatliu avatar xcatliu commented on May 9, 2024

这条规则只有在 if 里面有 return 语句的时候才会生效,所以并不能有效的避免回调地狱。

避免回调地狱的方式,eslint 已经提供了:max-nested-callbacks

from eslint-config-alloy.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.