注释
优质
小牛编辑
139浏览
2023-12-01
注释
只对存在一定业务逻辑复杂性的代码进行注释
注释并不是必须的,好的代码是能够让人一目了然,不用过多无谓的注释。
反例:
function hashIt(data) {
// The hash
var hash = 0;
// Length of string
var length = data.length;
// Loop through every character in data
for (var i = 0; i < length; i++) {
// Get character code.
var char = data.charCodeAt(i);
// Make the hash
hash = ((hash << 5) - hash) + char;
// Convert to 32-bit integer
hash = hash & hash;
}
}
正例:
function hashIt(data) {
var hash = 0;
var length = data.length;
for (var i = 0; i < length; i++) {
var char = data.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
// Convert to 32-bit integer
hash = hash & hash;
}
}
不要在代码库中遗留被注释掉的代码
版本控制的存在是有原因的。让旧代码存在于你的 history 里吧。
反例:
doStuff();
// doOtherStuff();
// doSomeMoreStuff();
// doSoMuchStuff();
正例:
doStuff();
不需要版本更新类型注释
记住,我们可以使用版本控制。废代码、被注释的代码及用注释记录代码中的版本更新说明都是没有必要的。
需要时可以使用 git log
获取历史版本。
反例:
/**
* 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;
}
正例:
function combine(a, b) {
return a + b;
}
避免位置标记
这些东西通常只能代码麻烦,采用适当的缩进就可以了。
反例:
////////////////////////////////////////////////////////////////////////////////
// Scope Model Instantiation
////////////////////////////////////////////////////////////////////////////////
let $scope.model = {
menu: 'foo',
nav: 'bar'
};
////////////////////////////////////////////////////////////////////////////////
// Action setup
////////////////////////////////////////////////////////////////////////////////
let actions = function() {
// ...
}
正例:
let $scope.model = {
menu: 'foo',
nav: 'bar'
};
let actions = function() {
// ...
}
避免在源文件中写入法律评论
将你的 LICENSE
文件置于源码目录树的根目录。
反例:
/*
The MIT License (MIT)
Copyright (c) 2016 Ryan McDermott
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
*/
function calculateBill() {
// ...
}
正例:
function calculateBill() {
// ...
}