最新公告
  • 欢迎您光临起源地模板网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入钻石VIP
  • 花五分钟把代码注释也规范一哈子?

    正文概述 掘金(掘金安东尼)   2021-02-22   449

    【注释】从技术上来说没有对错,理论上,你想怎么写就怎么写,你爱怎么写就怎么写!

    但它确实也会对我们造成影响,尤其是在多人协同开发的系统中。杂乱的注释也会让你或你的队友头疼~

    所以,我们需要规范一下注释。那什么才是好的注释呢?我们先来看看什么是不好的注释!

    注释冗余

    我们往往会写一段注释来说明“这是什么”。比如:

    // Find all the users
    let users = userHelper.findAll();
    
    // Add score to each user
    users.forEach((user) => {
    	user.score++;
    }
    						
    // Return the users
    return users;
    

    但是这段代码本身的意思就很清楚了,再附上注释就有点多余了。

    所以我们应该将其剔除。

    let users = userHelper.findAll();
    
    users.forEach((user) => {
    	user.score++;
    }
    						
    return users;
    

    那么,这段代码是不是就方便阅读了呢?其实,咱们还能更进一步:

    let users = userHelper.findAll();
    userHelper.incrementScoreForAll(users);						
    return users;
    

    这样你感觉如何?相比于最开始的那段代码,这段是不是就看得舒舒服服

    注释未更新

    // Find all users
    let users = userHelper.findBanned();
    
    // Give each user 100 extra score
    users.forEach((user) => {
    	user.score = 0;
    }
    
    return users;
    

    我们有时候会发现注释和代码并不匹配,比如这里为用户设置分数的操作。代码中是 0 分,注释却是 100 分。

    导致出现这种情况有多种可能:

    1. 我们总是在从其它地方复制代码,有时也会一并复制注释,然后在为己所用的过程中,修改了代码却没有修改对应的注释。
    2. 我们同时也在不断的根据产品需求调整代码(比如此处设置分值),修改代码也可能会忘记修改之前写的注释。

    怎么办?让我们来看看优解:

    // userHelper.js
    function updateScoreForUsers(score, users) {
      users.forEach((user) => {
    	  user.score += score;
      }
    }
    
    // Code 1: punish banned users
    let users = userHelper.findBanned();
    userHelper.updateScoreForUsers(users, -100);
    return users;
    
    // Code 2: give everybody 1 extra score
    let users = userHelper.findAll();
    userHelper.updateScoreForUsers(users, 1);
    return users;
    

    这样写将设置分数的逻辑封装成函数进行了抽离,功能更强了,也更易于阅读了。

    现在,我们可以在多种情况下重复调用它,且不必担心注释未及时更新的问题了。

    注释太长

    请问如果是这样的注释,你还有信心整个完整读下来吗?即使你是一个勇敢坚强的技术人,读下来也会消耗很多时间吧?这样低效率的事肯定不是我们想要的。

    // userHelper.js
    /**
     * Mass updates the user score for the given a list of user
     * The score will be updated by the amount given in the parameter score
     * For example, if the parameter score is 5, the users will all receive 5 extra score
     * But if the score is negative, it can also be used. In that case, the score will be decreased by 5.
     * If you set score as 0, then this method will be useless as nothing will be updated.
     * If you set the score as a non number value, the function will not do anything and return false
     * just to ensure the score is not messed up after updating it with a non-number value
     * Try to avoid using non-number values in the score parameter as this should not be used like that
     * If you do however choose to use Infinity in the score argument, it will work, because Infinity is considered as a number in JavaScript
     * If you set the score to Infinity, all the users score will become Inifinity, because n + Infinity where n is a number, will always result in Infinity
     * Regarding the users, make sure this is an array! If it is not an array, we will not process the users score,
     * then our method will simply return false instead and stop processing
     * Also make sure the users array is a list of actual user objects, we do not check this, but make sure the object has all the required fields as expected
     * especially the score object is important in this case.
     * @returns {boolean} Returns true if successful, false if not processed.
     */
    function updateScoreForUsers(score, users) {
      if (isNaN(score) || typeof users !== 'array') { return false; }
      
      users.forEach((user) => {
    	  user.score += score;
      }
                    
      return true;
    }
    

    所以,请确保你的注释不要太长。有那么多想说的,可以写文档、可以写文章,不要写注释~

    简单直接是最迷人的!

    注释太短

    这是另一个极端的例子,但是它确实源自于现实的开发项目中。

    // userHelper.js
    /**
     * Update score
     * @returns {boolean} result
     */
    function updateScoreForUsers(score, users) {
      if (isNaN(score) || typeof users !== 'array') { return false; }
      
      users.forEach((user) => {
    	  user.score += score;
      }
                    
      return true;
    }
    

    此段代码注释只是说明了返回值,但是更为关键的传参并未作出释义。显得有些尴尬~

    如果你决定注释,那就不要只写一半。请尽量准确、完整、干净的将其写出。从长期来看,你一定会从中受益。

    好的注释

    比如:

    // userHelper.js
    function updateScoreForUsers(score, users) {
      users.forEach((user) => {
        user.score += score;
        
        // VIPs are promised 500 extra score on top
        if (user.type == 'VIP') {
          user.score += 500;
        }
      }
                    
      return true;
    }
    

    此例中我们可以明白 VIP 用户是被产品要求多加 500 分值的。这样其它开发就不会对此产生疑惑。

    如果代码由多个团队维护,简单直接的小标注就更为必要了!

    小结

    注释在代码中扮演很重要的角色。本瓜还记得大学老师说:注释应该占代码的三分之一。

    我们都有不同的注释习惯,但是也应该有一个基本的指导:

    1. 注释应当简短、清晰,长篇大论稍边边。
    2. 告诉大家你 “为什么” 写这个注释,而不是告诉大家这段代码 “是什么”“是什么” 应该交给代码本身去解释。这个最为关键!
    3. 保持你的注释持久维护,也就是记得及时更新和与代码匹配。

    以上!

    撰文不易,点赞鼓励。讨论留言,携手向前。★,°:.☆( ̄▽ ̄)/$:.°★

    求一波关注,我的公众号:【掘金安东尼】,牛年持续更新~


    起源地下载网 » 花五分钟把代码注释也规范一哈子?

    常见问题FAQ

    免费下载或者VIP会员专享资源能否直接商用?
    本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
    提示下载完但解压或打开不了?
    最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。若排除这种情况,可在对应资源底部留言,或 联络我们.。
    找不到素材资源介绍文章里的示例图片?
    对于PPT,KEY,Mockups,APP,网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
    模板不会安装或需要功能定制以及二次开发?
    请QQ联系我们

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者

    请选择支付方式

    ×
    迅虎支付宝
    迅虎微信
    支付宝当面付
    余额支付
    ×
    微信扫码支付 0 元