花5分钟规范「代码注释」

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

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

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

注释冗余

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

// 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. 保持你的注释持久维护,也就是记得及时更新和与代码匹配。

本文来自投稿,不代表重蔚自留地立场,如若转载,请注明出处https://www.cwhello.com/35921.html

如有侵犯您的合法权益请发邮件951076433@qq.com联系删除

(0)
小二小二加盟商
上一篇 2022年5月13日 23:01
下一篇 2022年5月13日 23:07

相关推荐

  • 基于OpenCV实战:对象跟踪

    介绍跟踪对象的基本思想是找到对象的轮廓,基于HSV颜色值。轮廓:突出显示对象的图像片段。例如,如果将二进制阈值应用于具有(180,255)的图像,则大于180的像素将以白色突出显示,而其他则为黑色。白色部分称为轮…

    2022年4月27日 科技动态
    0166
  • 又一大厂裁员!当天粗暴通知赔偿N+1?小红书回应了...

    大厂们陆陆续续都在裁员,这次是轮到了小红书?近日,小红书被曝裁员的消息冲上微博热搜榜。据悉,相关员工在社交平台上爆料称,裁员全面启动,当天被通知last day。据脉脉上的相关爆料,此次整体裁员20%,先从试用…

    2022年4月27日
    0227
  • 关于公司网页制作流程。

    1. 需求分析,2. 设计规划,3. 页面制作,4. 功能开发,5. 测试优化,6. 上线部署,7. 维护更新 (图片来源网络,侵删) 公司网页制作流程是一个复杂的过程,涉及到多个步骤和环节,以下是详细的公司网页制作流程:…

    2024年7月1日
    00
  • 基于 Openpose 实现人体动作识别

    作者|李秋键 出品|AI科技大本营(ID:rgznai100)引言伴随着计算机视觉的发展和在生活实践中的广泛应用,基于各种算法的行为检测和动作识别项目在实践中得到了越来越多的应用,并在相关领域得到了广泛的研究。在行为监…

    2022年4月27日 科技动态
    0440
  • GitHub上最强NLP的Python项目合集

    知乎上有人提问:GitHub 上有哪些有趣的关于 NLP 的Python项目?先来说说什么是NLP?自然语言处理(NLP)的重点是使计算机能够理解和处理人类语言。计算机擅长处理结构化数据,如电子表格;然而,我们写或说的很多信…

    2022年4月27日 科技动态
    0264
  • 机器学习|调参方法分享(建议收藏!!!)

    有小伙伴催更了...今天给大家分享一下机器学习调参的几种方法。首次给大家介绍一下什么是调参。调参其实是为了找到更好更优的超参数,而超参数呢,是算法或者模型在开始学习之前设置值的初始参数。超参数是在建立模…

    2022年4月27日
    0272
  • 机器学习|使用scikit-learn构建模型的万能模板

    算法工程师是伴随着人工智能火起来的一个领域。听着名字似乎门槛很高。但是,得益于Python生态下的包共享机制,机器模型构建的过程其实已经变得非常简单了,很多听起来牛逼的算法,其实根本不需要自己实现,甚至都…

    2022年4月27日 科技动态
    0155
  • 机器学习:多种梯度下降优化算法总结分析

    论文标题:An overview of gradient descent optimization algorithms原文链接:https://arxiv.org/pdf/1609.04747.pdfGithub:NLP相关Paper笔记和代码复现(https://github.com/DengBoCong/nlp-paper)说明:阅读…

    2022年4月27日 科技动态
    0165

联系我们

QQ:951076433

在线咨询:点击这里给我发消息邮件:951076433@qq.com工作时间:周一至周五,9:30-18:30,节假日休息