Clean Code – Chapter 5 Formatting
-
The Purpose of Formatting
Code formatting is about communication, and communication is the professional developer's first order of business.
-
Vertical Formatting
File size: less than 200~500 lines.
-
The Newspaper Metaphor
We would like a source file to be like a newspaper article. The name should be simple but explanatory. The topmost parts of the source file should provide the high-level concepts and algorithms. Details should increase as we move downward, until at the end we find the lowest level functions and details in the source file.
-
Vertical Openness Between Concepts
Each line represents an expression or a clause, and each group of lines represents a complete thought. Those thoughts should be separated from each other with blank lines.
Each blank line is a visual cue that identifies a new and separate concept.
-
Vertical Density
Lines of code that are tightly related should appear vertically dense.
-
Vertical Distance
Concepts that are closely related should be kept vertically close to each other.
-
Variable Declarations
Variables should be declared as close to their usage as possible.
-
Instance variables
Should be declared at the top of the class.
-
Dependent Functions
If one function calls another, they should be vertically close, and the caller should be above the callee, if at all possible.
-
Conceptual Affinity
- a direct dependence
- a similar operation
-
-
-
Horizontal Formatting
Line width: less than 100~120.
-
Horizontal Openness and Density
Use horizontal white space to disassociate things that are weakly related.
e.g.
public class Quadratic { public static double root1(double a, double b, double c) { double determinant = determinant(a, b, c); return (-b + Math.sqrt(determinant)) / (2*a); } public static double root2(double a, double b, double c) { double determinant = determinant(a, b, c); return (-b - Math.sqrt(determinant)) / (2*a); } private static double determinant(double a, double b, double c) { return b*b - 4*a*c; } }
这里的行间空白主要体现在:
- 赋值号
=
左右空格以突出赋值操作 - 函数各参数之间空格分隔
- 函数名与其后面的左括号不需要空格
- 各种运算符左右空格以突出对应的操作
上面代码有个特例就是乘号左右没有空白分隔。按照作者的解释,“它们属于较高优先级(high precedence)”。 这么写公式的逻辑看起来确实更清晰一些。可惜 Visual Studio 的格式化代码没有这么智能。
- 赋值号
-
Horizontal Alignment
No need. (used in assembly files)
-
Indentation
To make the hierarchy of scopes visible.
-
Dummy Scopes
Try to avoid them.
Make sure that the dummy body is properly indented and surrounded by braces.
Bad code:
while (dis.read(buf, 0, readBufferSize) != -1) ;
Good code:
while (dis.read(buf, 0, readBufferSize) != -1) { ; }
-
-
Team Rules
Every programmer has his own favorite formatting rules, but if he works in a team, then the team rules.