为AirBnBJavaScript样式指南注入灵感

No one sets out to write ugly, inconsistently-styled code. It just sort of happens.

没有人开始编写难看的,风格不一致的代码。 这只是某种情况。

Even as the only developer on a project, the more time that passes and the more code you crank out, the harder it gets harder to maintain a consistent code style.

即使作为项目的唯一开发人员,经过的时间越多,您编写的代码越多,维护一致的代码样式就越难。

That’s why you need a style guide.

这就是为什么您需要样式指南。

I’ve experienced first-hand how much more teams can accomplish after adopting a style guide.

我亲身经历了采用样式指南后可以完成多少团队。

You no longer need to make little style judgement calls throughout the day. Just consult the style guide.

您不再需要全天进行小小的风格判断调用。 只需查阅样式指南即可。

And when a teammate needs to maintain your code, it’s clean code that they can read and understand.

当队友需要维护您的代码时,他们可以阅读和理解的是干净的代码。

Adopting a style guide is one of the easiest things you can do to boost your code’s maintainability — which ultimately boosts your team’s productivity. So let’s explore the most popular way to do this.

采用样式指南是提高代码可维护性的最简单方法之一,这最终可以提高团队的生产力。 因此,让我们探索最流行的方法。

输入AirBnB + ESLint (Enter AirBnB + ESLint)

The JavaScript ecosystem offers a wide variety of tools and style guides. This should surprise no one. with JavaScript, we’ve come to expect a wide variety of everything.

JavaScript生态系统提供了各种各样的工具样式指南 。 这应该没有人感到惊讶。 使用JavaScript,我们可以期待各种各样的东西。

But as the ecosystem matures, experienced developers start to yearn for “the standard way” of doing things that more solidified ecosystems offer.

但是随着生态系统的成熟,经验丰富的开发人员开始渴望做“标准方式”来做更巩固的生态系统所提供的服务。

You’re of course welcome to spend a few days exploring the JavaScript ecosystem and comparing different tools, but I’ll try and save you some time: ESLint is the most popular JavaScript linting tool, and AirBnB’s style guide is the most widely-used style guide.

当然,欢迎您花几天时间探索JavaScript生态系统并比较不同的工具,但我会尽力为您节省一些时间ESLint是最受欢迎JavaScript 整理工具,而AirBnB的样式指南是使用最广泛的样式时尚指南。

For more details on adding ESLint to your project checkout this link.

有关将ESLint添加到项目中的更多详细信息,请查看此链接

Once you have that squared away, you can configure your project to enforce AirBnB’s style guide by installing their npm package:

摆平后,您可以通过安装项目的npm软件包来配置项目以实施AirBnB的样式指南:

npm install --save-dev eslint-config-airbnb

Add the following line in your .eslintrc file

.eslintrc文件中添加以下行

"extends": "airbnb"

And voilà! Your code is now subject the rules of the most popular JavaScript style guide. Happy coding!

和瞧! 现在,您的代码已遵循最流行JavaScript样式指南的规则。 编码愉快!

标准被高估 (Standards are overrated)

While I agree with most of the rules in the style guide, here is a list of overrides that I compiled. This is what the .eslintrc files in projects’ root folders look like:

虽然我同意样式指南中的大多数规则,但是这里列出了我编译的替代项。 这是项目根文件夹中的.eslintrc文件的样子:

Let me explain the reasoning behind each of these customizations in detail.

让我详细解释每种自定义背后的原因。

缩进 (Indentation)

The tabs VS spaces war can potentially ruin friendships, and possibly even sabotage romantic relationships.

VS太空战可能会破坏友谊,甚至可能破坏浪漫关系。

I prefer to indent my code 4 spaces, even though a vast majority of configs out there prefer an indentation of 2.

我宁愿缩进我的代码4个空格,尽管那里的绝大多数配置都喜欢缩进2。

My reasoning is that in order to write clean code, larger indentations give you a better visual representation of how deep the nesting is in your functions, and how many different branches you have.

我的理由是,为了编写简洁的代码,较大的缩进可以使您更好地直观地了解嵌套在函数中的深度以及有多少个不同的分支。

You definitely shouldn’t be nesting code deeper than 3 or 4 layers inside a JavaScript file (it’s a code smell). So having 4 spaces offers you better readability, while preserving other rules like keeping your code within a 80 or 120 character-per-line limit.

您绝对不应在JavaScript文件中嵌套比3或4层更深的代码(这是代码的味道)。 因此,拥有4个空格可以为您提供更好的可读性,同时保留其他规则,例如将代码保持在每行80或120个字符以内。

Also, indentation is one of the rules that breathes more “air” into AirBnB’s default style guide. As a result, your code doesn’t crowd on the left side of editor so badly.

此外,缩进是AirBnB默认样式指南中引入更多“空气”的规则之一。 结果,您的代码不会严重挤在编辑器的左侧。

间距 (Spacing)

This is probably the biggest deviation from the standard. I hate crowded code. I started writing code with extra space padding more than 2 years ago, and I never looked back.

这可能是与标准的最大偏差。 我讨厌拥挤的代码。 两年多以前,我开始用额外的空格填充来编写代码,而我从没有回头。

So what do those rules mean? Well, have a look at the following code. It technically respects the rules of AirBnB’s official style guide.

那么这些规则是什么意思? 好吧,看看下面的代码。 从技术上讲,它尊重AirBnB官方风格指南的规则。

I know, it’s a bit confusing. I tried looking for a medium complexity function from one of my codebases, but I had to obfuscate a lot of it, so don’t try to understand the logic behind the code (because there is none). Just try to read it. Try to focus, for example, on variables that are used in multiple places, when parameters are passed to functions, and where the function calls are.

我知道,这有点令人困惑。 我尝试从我的一个代码库中寻找中等复杂度的函数,但是我不得不对其进行大量混淆,因此不要尝试理解代码背后的逻辑(因为没有逻辑)。 只是尝试阅读它。 例如,尝试着重于在多个地方使用的变量,将参数传递给函数的时间以及函数调用的位置。

Now have a look at the same code, but with the extra spacing rules applied:

现在看一下相同的代码,但是应用了额外的间距规则:

I’m not saying that it’s highly readable now, but you can more easily identify where you have parameters sent to functions — especially around the curried functions.

我并不是说它现在具有很高的可读性,但是您可以更轻松地确定将参数发送到函数的位置,尤其是在咖喱函数周围。

Also check the difference between the 2- and the 4-space indentation in the two examples.

还要检查两个示例中2和4空间缩进之间的差异。

At first, these techniques might not seem like a big improvement. I encourage you to give them a try. I think you’ll quickly experience what a difference this makes.

最初,这些技术似乎没有很大的进步。 我鼓励您尝试一下。 我认为您会很快体验到这有什么不同。

报价大战 (Quote wars)

While the first two categories had some clear arguments, I must say that the single vs double quotes decision is a highly subjective one.

尽管前两类有一些明确的论点,但我必须说, 引号还是引号是一个非常主观的决定。

My preference for double quotes probably comes from working a lot with React, where you mix JavaScript with JSX tags. Since JSX is closer to HTML, the tendency is to add attributes between double quotes. So I started using double quotes for everything, just for consistency.

我更喜欢双引号可能是因为与React一起工作了很多,在这里您将JavaScript与JSX标签混合在一起。 由于JSX更接近HTML,因此倾向于在​​双引号之间添加属性。 因此,为了一致性,我开始对所有内容都使用双引号。

One thing I’ve noticed is that you’re much more likely to need to write a single quote inside a string of English text than a double quote (“I’m here”, “Don’t do that”). So double quotes might be more convenient in these cases.

我注意到的一件事是,与双引号相比,您更有可能需要在英文文本字符串中写一个单引号(“我在这里”,“请勿这样做”)。 因此,在这种情况下,双引号可能更方便。

代码安排 (Code Arrangement)

The official AirBnB style guide has a “no-use-before-define” rule, which throws an error if you try to use something before you define it. This is a good rule — especially for variables — because you should not rely on hoisting, and you should keep the temporal dead zone problem in mind when you use let and const.

官方的AirBnB样式指南具有“定义前禁止使用”规则,如果您在定义之前尝试使用某些东西,则会引发错误。 这是一个很好的规则-特别是对于变量-因为您不应该依赖提升,并且在使用let和const时应牢记暂时的死区问题。

I prefer to allow functions be used before they’re defined. The reason is simple: most of the time, you will break your functions down into smaller sub-functions. However, the “no-use-before-define” rule will tell you to put these sub-functions before the original function.

我更喜欢在定义函数之前先使用它们。 原因很简单:大多数时候,您会将功能分解为较小的子功能。 但是,“定义前不能使用”规则将告诉您将这些子功能放在原始功能之前

But your sub-functions are there to abstract parts of the algorithm. They should not bother you when you open a file containing your top-level function, which you use outside of the file.

但是您的子功能在那里可以抽象算法的各个部分。 当您打开包含顶层函数的文件时,它们不会打扰您,您可以在文件外部使用该函数

Of course, this is debatable. But it does impact debugging. When you iterate over some code, and you find a call to a different function, ideally you should be able to look below it, or — worst case scenario — scroll down through a few sub-functions and find what you’re looking for.

当然,这是有争议的。 但这确实会影响调试。 当您遍历某些代码并找到对另一个函数的调用时,理想情况下,您应该可以在其下面查找,或者(在最坏的情况下)可以向下滚动一些子功能并找到所需的内容。

This, in combination with AirBnB’s function declaration against function expression rule, can give you the freedom to structure your modules or function libraries as you like, while ensuring you don’t accidentally call an uninitialized function.

结合AirBnB 针对函数表达式函数声明 规则, 可以让您自由地构造模块或函数库,同时确保您不会意外调用未初始化的函数。

const让 (Const over let)

Here’s another small deviation from the style guide. You can notice in my config:

这是与样式指南的另一个小偏差。 您可以在我的配置中注意到:

"prefer-const": 1

In the AirBnB config, this is set to 2, which stands for error, while 1 stands for warning.

在AirBnB配置中,此值设置为2,代表错误 ,而1代表警告

Now, if you don’t understand why you should prefer const over let, you can read more about it here and here.

现在,如果您不了解为什么比let更喜欢const,那么可以在这里这里阅读有关它的更多信息。

Regarding my deviation, I prefer a warning, because there are situations in which you do not change the assignment of a variable, but you change a lot of its content.

关于我的偏差,我更喜欢警告,因为在某些情况下,您不更改变量的赋值,而是更改了变量的很多内容。

Have a look at this code:

看一下这段代码:

The rules will tell you that this is right — hash should be const because it is not re-assigned. But this never really made sense to me. I should be aware that there’s a great deal of change happening inside hash.

规则将告诉您这是正确的- 哈希应该为const,因为它没有被重新分配。 但这对我来说从来没有真正意义。 我应该意识到, 哈希内部发生了很多变化

So I will use let to signal the fact that the variable is subject to change. const and let should lend more meaning to your variables, and should not hide the truth in any way.

因此,我将使用let来表示变量可能会更改的事实。 constlet应该为变量赋予更多含义,并且不应该以任何方式隐藏事实。

代码复杂度 (Code Complexity)

You can cyclomatic code complexity to compute the complexity of each of your functions.

您可以使用循环代码复杂度来计算每个函数的复杂度。

Deciding on a max level of complexity is tricky. Ideally it should be as low as possible, meaning that your functions should have at most 1 or 2 branching possibilities.

确定最大级别的复杂性很棘手。 理想情况下,它应尽可能低,这意味着您的函数最多应具有1或2个分支可能性。

It makes sense to have that number as low as possible from the perspective of code reuse and testing. But there are times when it’s harder to break functions down. That’s why I see the complexity more as a warning then as an error.

从代码重用和测试的角度来看,使该数字尽可能低是有意义的。 但是有时候很难分解功能。 这就是为什么我将复杂性更多地看作是警告而不是错误。

The important thing here is to limit the number of functions that reach that maximum complexity limit. Even in a medium-sized codebase, I wouldn’t like to see more than 10 functions that break this rule. So I picked the maximum value of 5, in order to highlight those functions. I’ll target these functions when I have time to do some refactoring.

这里重要的是限制达到最大复杂度限制的功能数量。 即使在中等大小的代码库中,我也不想看到超过10个违反该规则的函数。 因此,为了突出显示这些功能,我选择了最大值5。 有时间进行重构时,我将针对这些功能。

Complexity can be solved in multiple ways. Refactoring into smaller functions is the obvious one. Another option is transforming your switch statements into mapping assignments.

复杂性可以通过多种方式解决。 重构为较小的功能是显而易见的。 另一个选择是将switch语句转换为映射分配。

We had several debates inside our team, and we ended up using 5 as a reference value for the max complexity rule. But in some cases we go down to 4, just to be sure that we are writing clean and simple code.

我们的团队进行了几次辩论,最终以5作为最大复杂度规则的参考值。 但是在某些情况下,为了确保我们编写的是干净简单的代码,我们降低到了4。

关于React的说明 (A note on React)

Because I work a lot with React, and the AirBnB config also contains a hefty number of rules in that area, I wanted to include some of my preferences on these here, too.

因为我与React一起工作很多,并且AirBnB配置在该区域中还包含大量规则,所以我也想在此包含一些我的偏好。

The main goal of my React overrides is to limit the differentiation between regular JavaScript modules and React components, as well as between JavaScript code and JSX. That’s why I choose similar indentation and the use of double quotes for all JSX attributes. And that is why I prefer to leave all my files with the .js extension.

我的React重写的主要目标是限制常规JavaScript模块和React组件之间以及JavaScript代码和JSX之间的区别。 这就是为什么我选择类似的缩进并为所有JSX属性使用双引号。 这就是为什么我希望保留所有带有.js扩展名的文件的原因。

Finally, related to class vs factory components, I tend to prefer the latter. I see no advantage to using classes at this point. I may write a future post expanding on why I feel this way.

最后,关于类与工厂组件 ,我倾向于后者。 我认为此时使用类没有任何优势。 我可能会写一篇未来的文章,扩展我的感受。

That’s about it! I hope you enjoyed reading this. I welcome your feedback below.

就是这样! 希望您喜欢阅读。 我欢迎您在下面提供反馈。

If you liked the article, click on the green heart below, and I will know my efforts are not in vain.

如果您喜欢这篇文章,请单击下面的绿色心脏,我将知道我的努力没有白费。

翻译自: https://www.freecodecamp.org/news/adding-some-air-to-the-airbnb-style-guide-3df40e31c57a/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值