本文来自state-of-the-art-shitcode 垃圾代码书写准则
前几天逛githup的时候发现了这个仓库,教人如何写出垃圾的代码!
仓库已经有很久没有更新了我从项目的 issues、pr
等地方找到一些示例做了额外补充,愿大家好好学习努力成长!
一般准则
💩 以一种代码已经被混淆的方式命名变量
如果我们键入的东西越少,那么就有越多的时间去思考代码逻辑等问题。
Good 👍🏻
let a = 42;
复制代码
Bad 👎🏻
let age = 42;
复制代码
💩 以拼音进行命名 and 使用母语进行命名
英语什么的能有拼音来的舒服😌
某个项目的数据库全是 拼音简拼 sfzhm csrq 等等,还没注释一群人猜了好几天 痛苦不堪!
Good 👍🏻
let shuzi = 42;
// 拼音简拼
let sz = 42;
// 母语
let 数字 = 42;
复制代码
Bad 👎🏻
let age = 42;
复制代码
💩 变量/函数混合命名风格
为不同庆祝一下。
Good 👍🏻
let wWidth = 640;
let w_height = 480;
复制代码
Bad 👎🏻
let windowWidth = 640;
let windowHeight = 480;
复制代码
💩 不要写注释
反正没人会读你的代码。
Good 👍🏻
const cdr = 700;
复制代码
Bad 👎🏻
更多时候,评论应该包含一些“为什么”,而不是一些“是什么”。如果“什么”在代码中不清楚,那么代码可能太混乱了。
// 700ms的数量是根据UX A/B测试结果进行经验计算的。
// @查看: <详细解释700的一个链接>
const callbackDebounceRate = 700;
复制代码
💩 使用母语写注释
如果您违反了“无注释”原则,那么至少尝试用一种不同于您用来编写代码的语言来编写注释。如果你的母语是英语,你可能会违反这个原则。
Good 👍🏻
// Закриваємо модальне віконечко при виникненні помилки.
toggleModal(false);
复制代码
Bad 👎🏻
// 隐藏错误弹窗
toggleModal(false);
复制代码
💩 尽可能混合不同的格式
为不同庆祝一下。
Good 👍🏻
let i = ['tomato', 'onion', 'mushrooms'];
let d = [ "ketchup", "mayonnaise" ];
复制代码
Bad 👎🏻
let ingredients = ['tomato', 'onion', 'mushrooms'];
let dressings = ['ketchup', 'mayonnaise'];
复制代码
💩 尽可能把代码写成一行
节省空间,节省哪里的空间就不知道了
Good 👍🏻
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;
},
{}
)
复制代码
💩 不要处理错误
无论何时发现错误,都没有必要让任何人知道它。没有日志,没有错误弹框。
Good 👍🏻
try {
// 意料之外的情况。
} catch (error) {
// tss... 🤫
}
复制代码
Bad 👎🏻
try {
// 意料之外的情况。
} catch (error) {
setErrorMessage(error.message);
// and/or
logError(error);
}
复制代码
💩 广泛使用全局变量
全球化的原则。
Good 👍🏻
let x = 5;
function square() {
x = x ** 2;
}
square(); // 现在x是25
复制代码
Bad 👎🏻
let x = 5;
function square(num) {
return num ** 2;
}
x = square(x); // 现在x是25
复制代码
💩 创建你不会使用的变量
以防万一。
Good 👍🏻
function sum(a, b, c) {
const timeout = 1300;
const result = a + b;
return a + b;
}
复制代码
Bad 👎🏻
function sum(a, b) {
return a + b;
}
复制代码
💩 如果可以,不要规定类型也不要做类型检查。
Good 👍🏻
function sum(a, b) {
return a + b;
}
// 在这里享受没有注释的快乐
const guessWhat = sum([], {}); // -> "[object Object]"
const guessWhatAgain = sum({}, []); // -> 0
复制代码
Bad 👎🏻
function sum(a: number, b: number): ?number {
// 当我们在JS中不做置换和/或流类型检查时,覆盖这种情况。
if (typeof a !== 'number' && typeof b !== 'number') {
return undefined;
}
return a + b;
}
// 这个应该在转换/编译期间失败。
const guessWhat = sum([], {}); // -> undefined
复制代码
💩 你应该有不能到达的代码
这是你的 "Plan B".
Good 👍🏻
function square(num) {
if (typeof num === 'undefined') {
return undefined;
}
else {
return num ** 2;
}
return null; // 这就是我的"b计划".
}
复制代码
Bad 👎🏻
function square(num) {
if (typeof num === 'undefined') {
return undefined;
}
return num ** 2;
}
复制代码
💩 三角法则
就像鸟巢巢巢巢巢巢巢巢巢一样~
Good 👍🏻
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) {
}
}
}
复制代码
💩 混合缩进
避免缩进,因为它们会使复杂的代码在编辑器中占用更多的空间。如果你不喜欢回避他们,那就和他们捣乱。
Good 👍🏻
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]);
});
})
复制代码
💩 不要锁住你的依赖项
以非受控方式更新每个新安装的依赖项。为什么坚持使用过去的版本,让我们使用最先进的库版本。
Good 👍🏻
$ ls -la
package.json
复制代码
Bad 👎🏻
$ ls -la
package.json
package-lock.json
复制代码
💩 函数长的比短的好
不要把程序逻辑分成可读的部分。如果IDE的搜索停止,而您无法找到所需的文件或函数,该怎么办?
- 把一万行代码放进一个文件里是个很棒的选择。
- 把一千行代码放进一个函数里也是一个不错的想法。
- 把库(比如第三方的库或者自己的轮子,还有一些工具、数据库、手写的 ORM 和 jQuery 脚手架)都放在一个'service.js'里也是 OK 的。
💩 不要测试你的代码
这是重复且不需要的工作。
💩 避免代码风格统一
编写您想要的代码,特别是在一个团队中有多个开发人员的情况下。这是“自由”原则。
💩 构建新项目不需要 README 文档
一开始我们就应该保持。
issues
里有人说state-of-the-art-shitcode这个项目肯定违反了不创建 README
文件的规则笑出了声!
💩 保存不必要的代码
不要删除不用的代码,最多注释掉。
💩 尝试使用保留字/关键字作为变量和函数名称
这可以让你的代码更“清晰”!
Good 👍🏻
function async()
{
var let = { await: "null", class: "undefined" };
for (let of in let) console.log(of + let[of]);
}
复制代码
Bad 👎🏻
function my_async()
{
var let_to_do = { if_await: "null", type: "undefined" };
for (let oF in let_to_do) console.log(oF + let_to_do[oF]);
}
复制代码
💩 把布尔值都命名为 flag
给你同事思考的空间,让他们想想这个布尔值到底指的啥。
Good 👍🏻
let flag = true;
复制代码
Bad 👎🏻
let isDone = false;
let isEmpty = false;
复制代码
💩 在没有上下文的情况下使用神奇的数字
它看起来很神秘不是吗?
let timeOut = 42;
复制代码
Bad 👎🏻
let timeOutSeconds = 42;
复制代码
💩 使用表情符号作为标识符进行命名
随意表达你的感受。
Good 👍🏻
let ʘ‿ʘ = 42;
let ಠ_ಠ = 2022;
复制代码
Bad 👎🏻
let age = 42;
let year = 2022;
复制代码
💩 总是用团队成员很少使用的语言写评论。 以便成员可以轻松识别谁编写了代码。
- 如果您知道如何使用精灵语,请始终使用
- 如果你是唯一的中国人,那就用中文
- 如果您不懂其他语言,请尽可能使用家庭术语
开发接口服务 准则
💩 不要遵循 url 层次结构约定
少思考,多编码
Good 👍🏻
app.get('/e-workers', ()=>{})
app.get('/e-members', ()=>{})
复制代码
Bad 👎🏻
app.get('/explore/workers', ()=>{})
app.get('/explore/members', ()=>{})
复制代码
💩 始终将代码保存在一个文件中
通过将所有项目编码在一个文件中来保持项目井井有条
Good 👍🏻
app.get('/',()=>{})
app.get('/foo',()=>{})
app.get('/bar',()=>{})
app.get('/users',()=>{})
复制代码
Bad 👎🏻
import users from './routes/users';
app.use('users', users);
复制代码
💩 永远不要使用 PUT-DELETE-PATCH 方法
只有经验丰富的程序员才知道您的应用程序中只需要 GET 或 POST 请求,无需额外的混乱
Good 👍🏻
app.post('/createUser/:id',()=>{})
app.post('/EditUserData/:id',()=>{})
app.post('/DeleteUser/:id',()=>{})
复制代码
Bad 👎🏻
app.post('/user/:id',()=>{})
app.put('/user/:id',()=>{})
app.delete('/user/:id',()=>{})
复制代码
💩 始终保持端点名称尽可能短
url 名称中的字符越少,系统持久性越高
Good 👍🏻
app.get('/l',()=>{})
app.get('/s',()=>{})
app.get('/uv',()=>{})
复制代码
Bad 👎🏻
app.get('/login',()=>{})
app.get('/signup',()=>{})
app.get('/user/validate',()=>{})
复制代码
💩 您始终可以在 GET 请求中接收 JSON
如果您选择使用 GET 请求而不是 post 来处理所有请求,那么最好在查询参数中接收 JSON 对象
Good 👍🏻
// get -> 127.0.0.1:3000/l?json={"app":"cool"}
app.get('/l', (req, res)=>{
let json = req.params['json'];
let jsonParsed = JSON.parse(json);
})
复制代码
Bad 👎🏻
app.post('/l', (req, res)=>{
let json = req.body;
})
复制代码
vue准则
v-for 不要写 key
💩 不要单独查询详情
这个是从pr(提交一个我们公司同事写的烂代码)里找到的
Good 👍🏻
<!-- List.vue -->
<template>
<div @click="$router.push({name:'detail',query:{data}})">
<div class="title">{{data.title}}</div>
<div class="date">{{data.date}}</div>
</div>
</template>
<!-- Detail.vue -->
<template>
<div>
<div class="content" v-html="data.content"></div>
</div>
</template>
<script>
export default{
create(){
this.data = this.route.query.data;
}
}
</script>
复制代码
Bad 👎🏻
<!-- List.vue -->
<template>
<div @click="$router.push({name:'detail',query:{id}})">
<div class="title">{{data.title}}</div>
<div class="date">{{data.date}}</div>
</div>
</template>
<!-- Detail.vue -->
<template>
<div>
<div class="content" v-html="notice.content"></div>
</div>
</template>
<script>
export default{
data(){
return{
notice:{}
}
},
methods:{
getDetail(id){
http.getDetail({id}).then(res=>{
if(res.code==200){
this.notice = res.data;
}
})
}
},
mounted(){
let id = this.$route.query.id;
this.getDetail(id);
}
}
</script>
复制代码