• 代码整洁之道——9、格式化


    格式化是主观的。就像这里的很多规则,没有你必须遵守的硬性规则。主要观点是:不要因为格式去争论。这里有大量的自动化格式工具(tons of tools )。使用一个,程序员们为格式争论就是浪费时间。

    针对自动格式化工具不能覆盖的问题(缩进、 制表符还是空格、 双引号还是单引号等), 这里有一些指南。

    一、大小写一致

    js是一种弱类型语言,所以大小写可以告诉你变量、函数等很多事情。这些规则是主观的,所以你们团队可以任选。主要观点是,无论你们选择什么,要一致。

    Bad:
    const DAYS_IN_WEEK = 7;
    const daysInMonth = 30;
    
    const songs = ['Back In Black', 'Stairway to Heaven', 'Hey Jude'];
    const Artists = ['ACDC', 'Led Zeppelin', 'The Beatles'];
    
    function eraseDatabase() {}
    function restore_database() {}
    
    class animal {}
    class Alpaca {}
    
    Good:
    const DAYS_IN_WEEK = 7;
    const DAYS_IN_MONTH = 30;
    
    const SONGS = ['Back In Black', 'Stairway to Heaven', 'Hey Jude'];
    const ARTISTS = ['ACDC', 'Led Zeppelin', 'The Beatles'];
    
    function eraseDatabase() {}
    function restoreDatabase() {}
    
    class Animal {}
    class Alpaca {}

    二、调用函数和被调用的函数应该近一些

    如果一个函数调用另一个函数,保持这些函数在代码中垂直接近。理想的情况是调用函数在被调用函数上面。我们读代码就像读报纸一样,自上而下。正是这个原因,让你的代码像读的时候一样。

    Bad:
    //顺序乱
    class PerformanceReview {
      constructor(employee) {
        this.employee = employee;
      }
    
      lookupPeers() {
        return db.lookup(this.employee, 'peers');
      }
    
      lookupManager() {
        return db.lookup(this.employee, 'manager');
      }
    
      getPeerReviews() {
        const peers = this.lookupPeers();
        // ...
      }
    
      perfReview() {
        this.getPeerReviews();
        this.getManagerReview();
        this.getSelfReview();
      }
    
      getManagerReview() {
        const manager = this.lookupManager();
      }
    
      getSelfReview() {
        // ...
      }
    }
    
    const review = new PerformanceReview(employee);
    review.perfReview();
    
    Good:
    //顺序自上而下,调用函数在被调用函数上面
    class PerformanceReview {
      constructor(employee) {
        this.employee = employee;
      }
    
      perfReview() {
        this.getPeerReviews();
        this.getManagerReview();
        this.getSelfReview();
      }
    
      getPeerReviews() {
        const peers = this.lookupPeers();
        // ...
      }
    
      lookupPeers() {
        return db.lookup(this.employee, 'peers');
      }
    
      getManagerReview() {
        const manager = this.lookupManager();
      }
    
      lookupManager() {
        return db.lookup(this.employee, 'manager');
      }
    
      getSelfReview() {
        // ...
      }
    }
    
    const review = new PerformanceReview(employee);
    review.perfReview();
  • 相关阅读:
    JavaScript-数学对象与定时器
    JavaScript(八)-字符串与数组
    嵌入式的笔试题目(1)
    更改登录使用的默认shell的方法
    查看当前Linux 命令行使用的shell 的方法
    启动引导程序 Bootloader
    Debian 系(Deepin, Ubuntu, Linuxmint等)包管理工具
    ubuntu 服务器 samba 局域网内 如何添加samba user
    win10 和 树莓派3b+ 处于同一wifi环境(同一网段), win10 无法ping 通 树莓派3b+
    数据结构概念
  • 原文地址:https://www.cnblogs.com/xxchi/p/7243840.html
Copyright © 2020-2023  润新知