浏览 764
扫码
评论
仅仅对包含复杂业务逻辑的东西进行评论
评论是代码的辩解, 不是要求。 多数情况下, 好的代码就是文档。
不好的:
function hashIt(data) {// The hashlet hash = 0;// Length of stringconst length = data.length;// Loop through every character in datafor (let i = 0; i < length; i++) {// Get character code.const char = data.charCodeAt(i);// Make the hashhash = ((hash << 5) - hash) + char;// Convert to 32-bit integerhash &= hash;}}
好的:
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 integerhash &= hash;}}
不要在代码库中保存注释掉的代码
因为有版本控制, 把旧的代码留在历史记录即可。
不好的:
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////////////////////////////////////////////////////////////////////////////////$scope.model = {menu: 'foo',nav: 'bar'};////////////////////////////////////////////////////////////////////////////////// Action setup////////////////////////////////////////////////////////////////////////////////const actions = function() {// ...};
好的:
$scope.model = {menu: 'foo',nav: 'bar'};const actions = function() {// ...};