JavaScript清洁代码-快速最佳做法

介绍 (Introduction)

If you care about the code itself and how it’s written, instead only worrying does it work or not, you can say that you practice and care about the clean code.

如果您关心代码本身及其编写方式,而不必担心它是否起作用,那么您可以说您在实践并关心干净的代码

A professional developer will write the code for the future self and for the “other guy” not just for the machine

专业的开发人员将为未来的自我和“其他人”编写代码,而不仅仅是为机器编写代码

Based on that, the clean code can be defined as the code written in such a manner that is self-explanatory, easy to understand by humans and easy to change or extend.

基于此,干净的代码可以定义为以不言自明,易于人类理解,易于更改或扩展的方式编写代码

Even bad code can function, but if the code isn’t clean, it can bring a development organization to its knees.

甚至错误的代码也可以起作用,但是如果代码不干净,它可能会使开发组织屈服。

In this article, the focus will be on JavaScript, but the principles can be applied to other programming languages.

在本文中,重点将放在JavaScript上但是这些原理可以应用于其他编程语言。

1.强类型检查 (1. Strong type checks)

Use === instead of ==

使用===代替==

2.变量 (2. Variables)

Name your variables in a way that they reveal the intention behind it

为变量命名,以揭示其背后的意图

This way they become searchable and easier to understand after a person sees it.

这样,当人们看到它们后,它们就变得可搜索并且更易于理解。

Bad 👎

不好 👎

Good 👍

👍

不要在变量名中添加多余的单词 (Don’t add extra unneeded words to the variable names)

Bad 👎

不好 👎

let nameValue;let theProduct;

Good 👍

👍

let name;let product;

不必强制记住变量上下文 (Don’t enforce the need for memorizing the variable context)

Bad 👎

不好 👎

Good 👍

👍

不要添加不必要的上下文 (Don’t add unnecessary context)

Bad 👎

不好 👎

Good 👍

👍

对相同类型的变量使用相同的词汇表 (Use the same vocabulary for the same type of variable)

Bad 👎

不好 👎

getUserInfo();getClientData();getCustomerRecord();

Good 👍

👍

getProduct();

3.功能 (3. Functions)

Use long and descriptive names.

使用描述性的长名称。

Considering that it represents a certain behavior, a function name should be a verb or a phrase fully exposing the intent behind it as well as the intent of the arguments.

考虑到它代表某种行为,函数名称应该是动词或短​​语,以充分暴露其背后的意图以及参数的意图。

Their name should say what they do.

他们的名字应该说明他们在做什么。

Bad 👎

不好 👎

function email(user) {
// implementation
}

Good 👍

👍

function sendEmailUser(emailAddress) {
// implementation
}

避免大量争论 (Avoid a long number of arguments)

Ideally, a function should have two or fewer arguments specified.

理想情况下,函数应指定两个或更少的参数。

The fewer the arguments, the easier is to test the function.

参数越少,测试功能就越容易。

Bad 👎

不好 👎

function getProducts(fields, fromDate, toDate) {
// implementation
}

Good 👍

👍

使用默认参数代替条件 (Use default arguments instead of conditionals)

Bad 👎

不好 👎

function createShape(type) {
const shapeType = type || "circle";
// ...
}

Good 👍

👍

function createShape(type = "circle") {
// ...
}

避免在一个函数中执行多个动作 (Avoid executing multiple actions within a single function)

Bad 👎

不好👎

Good 👍

👍

使用' Object.assign'设置默认对象 (Use 'Object.assign’ to set default objects)

Bad 👎

不好 👎

Good 👍

👍

不要将标志用作参数,因为它们会告诉您该函数的作用超出应有的程度 (Don’t use flags as parameters because they are telling you that the function is doing more than it should)

Bad 👎

不好 👎

Good 👍

👍

不要污染全球 (Don’t pollute the Globals)

If you need to extend an existing object use ES Classes and inheritance instead of creating the function on the prototype chain of the native object.

如果需要扩展现有对象,请使用ES类和继承,而不要在本机对象的原型链上创建函数。

Bad 👎

不好 👎

Array.prototype.myFunction = function myFunction() {
// implementation
};

Good 👍

👍

class SuperArray extends Array {
myFunc() {
// implementation
}
}

4.条件 (4. Conditionals)

Avoid negative conditionals.

避免负面条件。

Bad 👎

不好 👎

function isPostNotPublished(post) {
// implementation
}if (!isPostNotPublished(post)) {
// implementation
}

Good 👍

👍

function isPostPublished(user) {
// implementation
}if (isPostPublished(user)) {
// implementation
}

使用条件速记 (Use conditional shorthand)

This might be trivial, but it’s worth mentioning.

这可能是微不足道的,但值得一提。

Use this approach only for boolean values and if you are sure that the value will not be undefined or null.

如果您确定该值不会是undefinednull ,则仅对布尔值使用此方法。

Bad 👎

不好 👎

if (isValid === true) {
// do something...
}if (isValid === false) {
// do something...
}

Good 👍

👍

if (isValid) {
// do something...
}if (!isValid) {
// do something...
}

尽可能避免有条件 (Avoid conditionals whenever possible)

Use polymorphism and inheritance instead.

请改用多态继承

Bad 👎

不好 👎

Good 👍

👍

5. ES类 (5. ES Classes)

Classes are the new syntactic sugar in JavaScript.

类是JavaScript中新的语法糖。

Everything works just as it did before with prototype only it now looks different and you should prefer them over ES5 plain functions.

一切工作都与以前的原型一样,只是现在看起来有所不同,您应该更喜欢它们而不是ES5普通函数。

Bad 👎

不好 👎

Good 👍

👍

使用方法链接 (Use method chaining)

Many libraries such as jQuery and Lodash use this pattern.

jQueryLodash等许多库使用此模式。

As a result, your code will be less verbose.

结果,您的代码将不再那么冗长。

In your class, simply return this at the end of every function, and you can chain further class methods onto it.

在你的类,只需返回this在每个函数的结尾,你可以链至少还类的方法在其上。

Bad 👎

不好 👎

Good 👍

👍

6.避免使用评估 (6. Avoid Using Eval)

The Eval function allows us to pass a string to the JavaScript compiler and have it execute as JavaScript

Eval函数使我们可以将字符串传递给JavaScript编译器,并使它作为JavaScript执行

In simple terms, anything you pass in at runtime gets executed as if it were added at design time.

简而言之,您在运行时传递的任何内容都会像在设计时添加的那样执行。

eval("alert('Hi');");

This would pop up an alert box with the message “Hi” in it.

这将弹出一个警告框,其中显示消息“ Hi”。

Eval function should be avoided because it’s not safe and it opens a potential threat vector for malicious programmers to exploit.

应该避免使用评估函数,因为它不安全,并且为恶意程序员提供了潜在的威胁载体。

7.使用JSLint (7. Use JSLint)

JSLint is a great tool for helping you identify common problems in your JavaScript code, it will pick up bad code that is being masked by the browser.

JSLint是一个很好的工具,可帮助您识别JavaScript代码中的常见问题,它将获取浏览器掩盖的错误代码

You can use a different sites like JavaScriptLint.com, or you can use one of the many downloadable JSLint tools.

您可以使用JavaScriptLint.com之类的其他网站,也可以使用许多可下载的JSLint工具之一

For instance, Visual Studio has an add-in for JSLint that will allow you to check for errors at compile-time (or manually).

例如, Visual Studio有一个JSLint加载项 ,使您可以在编译时(或手动)检查错误。

This will make your code cleaner and it will help to prevent those pesky bugs from showing up in production.

这将使您的代码更整洁,并有助于防止那些讨厌的错误出现在生产中。

8.避免一般 (8. Avoid In General)

In general, you should do your best not to repeat yourself, meaning you shouldn’t write duplicate code, and not to leave tails behind you such as unused functions and dead code.

通常, 您应该尽最大努力不重复自己 ,这意味着您不应该编写重复的代码 ,也不要遗留诸如未使用的函数和无效代码之类的尾巴。

Removing duplicate code in this situation means to abstract the differences and handle them on that level.

在这种情况下,删除重复的代码意味着抽象出差异并在该级别上进行处理。

And about the dead code, well it is what its name says.

关于死代码 ,这正是它的名字所说的。

It's the code sitting there in our code base not doing anything because, at some point in development, you’ve decided that it no longer has a purpose.

这是我们代码库中没有执行任何操作的代码,因为在开发的某个时刻, 您已经确定它不再具有用途

You should search your codebase for these parts and delete all unneeded functions and code blocks.

您应该在代码库中搜索这些部分,并删除所有不需要的功能和代码块。

An advice I can give to you is as soon you decide it’s no longer needed, delete it.

我可以给您的建议是,一旦您确定不再需要它,请将其删除。

结论 (Conclusion)

This is only a fraction of what you could do to improve your code.

这只是您可以改进代码的一小部分。

In my opinion, the principles alleged here are the ones which people often don’t follow.

我认为,这里所说的原则是人们经常不遵循的原则。

They try to, but it’s not easy to maintain the mental strength and make a great code all the time.

他们尽力了, 但是要保持头脑的力量并始终保持出色的成绩并不容易

Maybe at the start of the project, the code is neat and clean but when it comes to meeting deadlines, the principles are often ignored and moved into a “TODO” or “REFACTOR” section.

也许在项目开始时,代码就很整洁,但是在截止日期之前,通常会忽略原则,而将其移至“ TODO”或“ REFACTOR”部分

Thank you for reading and see you in the next article!

感谢您阅读并在下一篇文章中见!

翻译自: https://medium.com/javascript-in-plain-english/javascript-clean-code-best-practices-461c24c53cae

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值