评论

仅仅对包含复杂业务逻辑的东西进行评论

评论是代码的辩解, 不是要求。 多数情况下, 好的代码就是文档。

不好的:

  1. function hashIt(data) {
  2. // The hash
  3. let hash = 0;
  4. // Length of string
  5. const length = data.length;
  6. // Loop through every character in data
  7. for (let i = 0; i < length; i++) {
  8. // Get character code.
  9. const char = data.charCodeAt(i);
  10. // Make the hash
  11. hash = ((hash << 5) - hash) + char;
  12. // Convert to 32-bit integer
  13. hash &= hash;
  14. }
  15. }

好的:

  1. function hashIt(data) {
  2. let hash = 0;
  3. const length = data.length;
  4. for (let i = 0; i < length; i++) {
  5. const char = data.charCodeAt(i);
  6. hash = ((hash << 5) - hash) + char;
  7. // Convert to 32-bit integer
  8. hash &= hash;
  9. }
  10. }

不要在代码库中保存注释掉的代码

因为有版本控制, 把旧的代码留在历史记录即可。

不好的:

  1. doStuff();
  2. // doOtherStuff();
  3. // doSomeMoreStuff();
  4. // doSoMuchStuff();

好的:

  1. doStuff();

不要有日志式的评论

记住, 使用版本控制! 不需要僵尸代码, 注释调的代码, 尤其是日志式的评论。 使用 git log
获取历史记录。

不好的:

  1. /**
  2. * 2016-12-20: Removed monads, didn't understand them (RM)
  3. * 2016-10-01: Improved using special monads (JP)
  4. * 2016-02-03: Removed type-checking (LI)
  5. * 2015-03-14: Added combine with type-checking (JR)
  6. */
  7. function combine(a, b) {
  8. return a + b;
  9. }

好的:

  1. function combine(a, b) {
  2. return a + b;
  3. }

避免占位符

它们仅仅添加了干扰。 让函数和变量名称与合适的缩进和格式化为你的代码提供视觉结构。

不好的:

  1. ////////////////////////////////////////////////////////////////////////////////
  2. // Scope Model Instantiation
  3. ////////////////////////////////////////////////////////////////////////////////
  4. $scope.model = {
  5. menu: 'foo',
  6. nav: 'bar'
  7. };
  8. ////////////////////////////////////////////////////////////////////////////////
  9. // Action setup
  10. ////////////////////////////////////////////////////////////////////////////////
  11. const actions = function() {
  12. // ...
  13. };

好的:

  1. $scope.model = {
  2. menu: 'foo',
  3. nav: 'bar'
  4. };
  5. const actions = function() {
  6. // ...
  7. };