• 代码整洁之道——10、注释


    一、只对复杂业务逻辑添加注释

    注释是代码的解释说明,不是必须的,好的代码本身就是文档。

    Bad:
    function hashIt(data) {
      // The hash
      let hash = 0;
    
      // Length of string
      const length = data.length;
    
      // Loop through every character in data
      for (let i = 0; i < length; i++) {
        // Get character code.
        const char = data.charCodeAt(i);
        // Make the hash
        hash = ((hash << 5) - hash) + char;
        // Convert to 32-bit integer
        hash &= hash;
      }
    }
    
    Good:
    function hashIt(data) {
      let hash = 0;
      const length = data.length;
    
      for (let i = 0; i < length; i++) {
        const char = data.charCodeAt(i);
        hash = ((hash << 5) - hash) + char;
    
        // Convert to 32-bit integer
        hash &= hash;
      }
    }

    二、不要把注释掉的代码放在代码库里

    版本控制的原因就是把老代码放在历史库中。

    Bad:
    doStuff();
    // doOtherStuff();
    // doSomeMoreStuff();
    // doSoMuchStuff();
    
    Good:
    doStuff();

    三、不要有日志式的注释

    记住,使用版本控制。不要有没用到的代码,注释掉的代码,尤其是日志式的注释。使用git log获取历史记录

    Bad:
    /**
     * 2016-12-20: Removed monads, didn't understand them (RM)
     * 2016-10-01: Improved using special monads (JP)
     * 2016-02-03: Removed type-checking (LI)
     * 2015-03-14: Added combine with type-checking (JR)
     */
    function combine(a, b) {
      return a + b;
    }
    
    
    Good:
    function combine(a, b) {
      return a + b;
    }

    四、避免占位符

    它们通常是添加了干扰,用合适的缩进和格式化让函数、变量提供一种视觉结构。

    Bad:
    ////////////////////////////////////////////////////////////////////////////////
    // Scope Model Instantiation
    ////////////////////////////////////////////////////////////////////////////////
    $scope.model = {
      menu: 'foo',
      nav: 'bar'
    };
    
    ////////////////////////////////////////////////////////////////////////////////
    // Action setup
    ////////////////////////////////////////////////////////////////////////////////
    const actions = function() {
      // ...
    };
    
    Good:
    $scope.model = {
      menu: 'foo',
      nav: 'bar'
    };
    
    const actions = function() {
      // ...
    };
  • 相关阅读:
    SDOI2020游记
    Git和GitHub详解
    P1251 餐巾计划问题
    P2824 [HEOI2016/TJOI2016]排序
    P3224 [HNOI2012]永无乡
    P3605 [USACO17JAN]Promotion Counting晋升者计数
    P4314 CPU监控
    P2939 [USACO09FEB]改造路Revamping Trails
    P4254 [JSOI2008]Blue Mary开公司
    P1772 [ZJOI2006]物流运输
  • 原文地址:https://www.cnblogs.com/xxchi/p/7243972.html
Copyright © 2020-2023  润新知