当前位置:网站首页>6 rules to sanitize your code

6 rules to sanitize your code

2022-08-09 23:14:00 51CTO

6A rule to purify your code_代码风格

Readable code's maintainability!

1、注重命名

Named for an event is difficult.Although difficult but very necessary.

想象以下,将两个数组合并成一个数组,And generate a unique value array.So what would you name it?We may be so named?

      
      
function mergeNumberListIntoUniqueList( listOne, listTwo) {
return [ ... new Set([ ... listOne, ... listTwo])]
}
  • 1.
  • 2.
  • 3.

The above named is not bad,But also is not very friendly.You can take a functions into two functions,This name is more friendly and function better reusability.

      
      
function mergeLists( listOne, listTwo) {
return [ ... listOne, ... listTwo]
}

function createUniqueList( list) {
return [ ... new Set( list)]
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

2、IF语句简化

Suppose we have the following code:

      
      
if( value === 'duck' || value === 'dog' || value === 'cat') {
// ...
  • 1.
  • 2.

我们可以这样解决:

      
      
const options = [ 'duck', 'dog', 'cat'];
if ( options. includes( value)) {
// ...
  • 1.
  • 2.
  • 3.

将乱七八糟的条件判断放到一个变量中存储,比看臃肿的表达式要好很多.

3、及早返回

有下面的代码:

      
      
function handleEvent( event) {
if ( event) {
const target = event. target;
if ( target) {
// Your awesome piece of code that uses target
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

Early returns makes our code more readable:

      
      
function handleEvent( event) {
if ( ! event || ! event. target) {
return;
}
// Your awesome piece of code that uses target
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

4、解构赋值

在​​javascript​​​中,我们可以对​​objects​​​和​​arrays​​进行解构赋值.

例如:

      
      
// object 解构赋值
const numbers = { one: 1, two: 2};
const { one, two} = numbers;
console. log( one); // 1
console. log( two); // 2

// array 解构赋值
const numbers = [ 1, 2, 3, 4, 5];
const [ one, two] = numbers;
console. log( one); // 1
console. log( two); // 2
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

5、童子军规则

童子军有一条规则:Always keep away camping cleaner than when you find it.如果你在地面上发现了脏东西,那么无论是否是你留下的,You have to clean it.你要有意地为下一组露营者改善环境.

我们编写代码也是这样子,If you are found in the code脏代码,那么你可以尝试去修改它,即使是一个没有被引用到的变量名.

6、代码风格

Used in your team一种代码风格,Such as limited code indentation specification is two Spaces or four Spaces;Using single quotes or double quotes;使用同类的一种框架呢,还是流行两种解决方案的框架呢...这样团队中人员接手项目的成本就会降低,开发人员的心里减少排斥感~


原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208092113597844.html