摘转自:机器之心,本文主要列举了那些让人窒息的代码习惯,拥有这些代码习惯的程序员总能写出不易于维护,并且不利于多人协调的代码,如果你的身边有人拥有以下多条代码习惯,请关爱他☠️。
在 GitHub 上有一个新项目,它描述了「最佳垃圾代码」的二十条关键准则。从变量命名到注释编写。这些准则将指导你写出最亮眼的烂代码。
💩 第一条:打字越少越好
let a = 42;
Bad 👎🏻
let age = 42;
💩 第二条:变量/函数混合命名风格
let wWidth = 640;
let w_height = 480;
Bad 👎🏻
let windowWidth = 640;
let windowHeight = 480;
💩第三条:不要写注释
const cdr = 700;
Bad 👎🏻
// The number of 700ms has been calculated empirically based on UX A/B test results.
// @see: <link to experiment or to related JIRA task or to something that explains number 700 in details>
const callbackDebounceRate = 700;
💩第四条:使用母语写注释
// Закриваємо модальне віконечко при виникненні помилки.
toggleModal(false);
Bad 👎🏻
// Hide modal window on error.
toggleModal(false);
💩第五条:尽可能混合不同的格式
let i = ['tomato', 'onion', 'mushrooms'];
let d = [ "ketchup", "mayonnaise" ];
Bad 👎🏻
let ingredients = ['tomato', 'onion', 'mushrooms'];
let dressings = ['ketchup', 'mayonnaise'];
💩第六条:尽可能把代码写成一行
document.location.search.replace(/(^\?)/,'').split('&').reduce(function(o,n){n=n.split('=');o[n[0]]=n[1];return o},{})
Bad 👎🏻
document.location.search
.replace(/(^\?)/, '')
.split('&')
.reduce((searchParams, keyValuePair) => {
keyValuePair = keyValuePair.split('=');
searchParams[keyValuePair[0]] = keyValuePair[1];
return searchParams;
},
{}
)
💩第七条:发现错误要保持静默
try {
// Something unpredictable.
} catch (error) {
// tss... 🤫
}
Bad 👎🏻
try {
// Something unpredictable.
} catch (error) {
setErrorMessage(error.message);
// and/or
logError(error);
}
💩第八条:广泛使用全局变量
let x = 5;
function square() {
x = x ** 2;
}
square(); // Now x is 25.
Bad 👎🏻
let x = 5;
function square(num) {
return num ** 2;
}
x = square(x); // Now x is 25.
💩第九条:构建备用变量
function sum(a, b, c) {
const timeout = 1300;
const result = a + b;
return a + b;
}
Bad 👎🏻
function sum(a, b) {
return a + b;
}
💩第十条:Type 使用需谨慎
function sum(a, b) {
return a + b;
}
// Having untyped fun here.
const guessWhat = sum([], {}); // -> "[object Object]"
const guessWhatAgain = sum({}, []); // -> 0
Bad 👎🏻
function sum(a: number, b: number): ?number {
// Covering the case when we don't do transpilation and/or Flow type checks in JS.
if (typeof a !== 'number' && typeof b !== 'number') {
return undefined;
}
return a + b;
}
// This one should fail during the transpilation/compilation.
const guessWhat = sum([], {}); // -> undefined
💩第十一条:准备「Plan B」
function square(num) {
if (typeof num === 'undefined') {
return undefined;
}
else {
return num ** 2;
}
return null; // This is my "Plan B".
}
Bad 👎🏻
function square(num) {
if (typeof num === 'undefined') {
return undefined;
}
return num ** 2;
}
💩第十二条:嵌套的三角法则
function someFunction() {
if (condition1) {
if (condition2) {
asyncFunction(params, (result) => {
if (result) {
for (;;) {
if (condition3) {
}
}
}
})
}
}
}
Bad 👎🏻
async function someFunction() {
if (!condition1 || !condition2) {
return;
}
const result = await asyncFunction(params);
if (!result) {
return;
}
for (;;) {
if (condition3) {
}
}
}
💩第十三条:混合缩进
const fruits = ['apple',
'orange', 'grape', 'pineapple'];
const toppings = ['syrup', 'cream',
'jam',
'chocolate'];
const desserts = [];
fruits.forEach(fruit => {
toppings.forEach(topping => {
desserts.push([
fruit,topping]);
});})
Bad 👎🏻
const fruits = ['apple', 'orange', 'grape', 'pineapple'];
const toppings = ['syrup', 'cream', 'jam', 'chocolate'];
const desserts = [];
fruits.forEach(fruit => {
toppings.forEach(topping => {
desserts.push([fruit, topping]);
});
})
💩第十四条:不要锁住依赖项
$ ls -la package.json
Bad 👎🏻
$ ls -la package.json package-lock.json
💩 第十五条:始终将布尔值命名为 flag
留出空间让您的同事去思考布尔值的含义。
Good 👍🏻
let flag = true;
Bad 👎🏻
let isDone = false;
let isEmpty = false;
💩第十六条:长函数比短函数好
💩第十七条:代码不需要做特定测试
💩第十八条:尽量避免重复代码
💩第十九条:构建新项目不需要 README 文档
💩第二十条:保存不必要的代码
本文来自投稿,不代表微擎百科立场,如若转载,请注明出处:https://www.w7.wiki/develop/3370.html