💩 打字越少越好
如果我们键入的东西越少,那么就有越多的时间去思考代码逻辑等问题。
Good 👍🏻
int a = 42;
Bad 👎🏻
int age = 42;
💩 变量/函数混合命名风格
为什么要规范命名变量,拥抱多样性!
Good 👍🏻
int wWidth = 640;
int w_height = 480;
Bad 👎🏻
int window_width = 640;
int window_height = 480;
💩 不要写注释
反正没人会读你的代码。
💩 使用母语写注释
如果您违反了”无注释”原则,那么至少尝试用一种不同于您用来编写代码的语言来编写注释。
Good 👍🏻
// Закриваємо модальне віконечко при виникненні помилки.
if (n <= 1) {
printf("不是素数");
return 0;
}
Bad 👎🏻
// 处理特殊情况
if (n <= 1) {
printf("不是素数");
return 0;
}
💩 尽可能把代码写成一行
Good 👍🏻
for(int i=0;i<10;i++){if(array[i]==target){printf("Found at %d",i);break;}}
Bad 👎🏻
for (int i = 0; i < 10; i++) {
if (array[i] == target) {
printf("Found at %d", i);
break;
}
}
💩 不要处理错误
无论何时发现错误,都没有必要让任何人知道它。
Good 👍🏻
FILE* file = fopen("data.txt", "r");
// 如果文件打开失败?无所谓!
Bad 👎🏻
FILE* file = fopen("data.txt", "r");
if (file == NULL) {
perror("Error opening file");
return -1;
}
💩 创建你不会使用的变量
以防万一。
Good 👍🏻
int sum(int a, int b) {
int unused1 = 100;
int unused2 = 200;
int result = a + b;
int unused3 = 300;
return a + b; // 等等,result变量呢?
}
Bad 👎🏻
int sum(int a, int b) {
return a + b;
}
💩 忽略类型安全
C语言已经很灵活了,为什么还要限制自己?
Good 👍🏻
void* mysterious_data = "hello";
int number = *((int*)mysterious_data); // 数据类型:惊喜!
Bad 👎🏻
const char* text = "hello";
// 使用正确的类型
💩 三角法则
就像鸟巢,鸟巢,鸟巢。
Good 👍🏻
void process_data() {
if (condition1) {
if (condition2) {
for (int i = 0; i < 10; i++) {
if (condition3) {
while (condition4) {
if (condition5) {
// 真正的逻辑在这里
}
}
}
}
}
}
}
Bad 👎🏻
void process_data() {
if (!condition1 || !condition2) {
return;
}
for (int i = 0; i < 10; i++) {
if (!condition3) continue;
while (condition4) {
if (!condition5) break;
// 真正的逻辑在这里
}
}
}
💩 混合缩进
避免一致的缩进,让代码看起来更有”个性”。
Good 👍🏻
int main(){
int x=5;
if(x>3){
printf("x is greater than 3");
if(x>10){
printf("and also greater than 10");
}
}
return 0;
}
Bad 👎🏻
int main() {
int x = 5;
if (x > 3) {
printf("x is greater than 3");
if (x > 10) {
printf("and also greater than 10");
}
}
return 0;
}
💩 函数长的比短的好
不要把程序逻辑分成可读的部分。
- 一个文件中5000行代码是OK的
- 一个函数体有500行代码是OK的
- 在main.c中处理所有事情?这是OK的
💩 不要测试你的代码
测试是给懦夫用的。真正的程序员直接部署到生产环境(或提交到考试系统)。
💩 保存不必要的代码
不要删除不用的代码,最多注释掉。
Good 👍🏻
/*
int old_function(int x) {
return x * 2; // 这个可能以后还会用到
}
*/
int new_function(int x) {
return x + 1; // 但我们现在用这个
// 不过把旧的留着,万一呢?
}
记住,写出好的垃圾C代码是一门艺术!祝你写出更多”优秀”的垃圾代码!