可读性与命名规范 » 代码简洁之道
许多人认为代码的可读性仅与使用的字母和符号有关。他们认为通过增删或修改这些符号就能提升可读性。从某种角度看,他们是对的。但底层原则其实是:代码的可读性主要取决于字母和符号所占用的空间布局。
这意味着两件事:
- 代码周围应有适量的空白——不多不少
- 代码行内部应有适当间距分隔不同部分
这个原则揭示了一个反直觉的真相:正是代码的缺失让代码变得可读。这是生活中的普遍原理——例如书中字母和单词间若没有间距将难以阅读;而夜空中明月之所以清晰可见,正是因为存在大量非月亮的黑色空间。同理,当代码具有合理的空间结构时,你能轻松定位和理解代码。
空间管理的艺术
糟糕的紧凑代码示例:
1
|
x=1+2;y=3+4;z=x+y;print"hello world";print"z is"+z;if(z>y+x){print"error";}
|
良好间距的改进版:
1
2
3
4
5
6
7
8
|
x = 1 + 2;
y = 3 + 4;
z = x + y;
print "hello world";
print "z is" + z;
if (z > y + x) {
print "error";
}
|
但空间过多或分布不当同样有害:
过度间距的反例:
1
2
3
4
5
6
7
8
9
10
|
x = 1+ 2;
y = 3 +4;
z = x + y;
print "hello world" ;
print "z is " + z;
if (z > y+x)
{ print "error" ;
}
|
核心原则:代码占用的空间应与其表达的含义成正比。
命名规范的精髓
过于简短的命名:
1
2
|
q = s(j, f, m);
p(q);
|
恰当的命名:
1
2
|
quarterly_total = sum(january, february, march);
print(quarterly_total);
|
过度冗长的命名:
1
2
|
quarterly_total_for_company_x_in_2011_as_of_today = add_all_of_these_together_and_return_the_result(january_total_amount, february_total_amount, march_total_amount);
send_to_screen_and_dont_wait_for_user_to_respond(quarterly_total_for_company_x_in_2011_as_of_today);
|
最佳实践是找到平衡点:
1
|
print_quarterly_total();
|
代码重构的智慧
原始代码块:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
x_pressed = false;
y_pressed = false;
if (input == "x") {
print "You pressed x!";
x_pressed = true;
}
else if (input == "y") {
if (not y_pressed) {
print "You pressed y for the first time!";
y_pressed = true;
if (x_pressed) {
print "You pressed x and then y!";
}
}
}
|
第一次重构:
1
2
3
4
5
6
7
8
|
x_pressed = false;
y_pressed = false;
if (input == "x") {
handle_x(x_pressed);
}
else if (input == "y") {
handle_y(x_pressed, y_pressed);
}
|
终极简化:
命名的黄金准则
著名程序员曾说过:“命名是计算机科学中最难的问题之一”。我们的可读性原则为此提供了指导:
- 变量/函数名应足够长以完整表达其含义
- 但不应过长导致阅读困难
- 需考虑使用场景:高频使用的名称应更简短
- 作用域越小,名称可越短(如循环变量)
记住:h(input)
太模糊,而handle_this_input_and_figure_out_if_it_is_x_or_y_and_then_do_the_right_thing(input)
则过于冗长。
(原文后续包含读者评论讨论,涉及SQL格式、垂直对齐、注释策略等延伸话题,此处从略)