Code formatting is about communication, and communication is the professional developer’s first order of business
Coding style and readability persist, even as the original codes are changed over time because of maintenance and extension needs.
Example of Java projects file length distributions:
What can we see from the graph?
Smaller files increase the code readability.
From top to bottom, it should be from high-level concepts and algorithms to details and low-level functions.
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.
then vertical density implies close association.
Example of "eye-full" codes, which means the reader can understand the codes without moving their eyes too much.
Should not make readers spend time searching for where are the codes when they try to understand what the system does.
their vertical separation should be a measure of how important each is to the understandability of the other.
Variables should be declared as close to their usage as possible.
Because our functions are very short, local variables should appear a the top of each function.
Control variables for loops should usually be declared within the loop statement.
should be declared at the top of the class.
the instance variables to be declared in one well-known place. Everybody should know where to go to see the declarations.
they should be vertically close, and the caller should be above the callee.
When some codes want to get closer to each other, it might be because:
The example from the book shows line lengths distribution (seven projects).
Assignment statements
Have spaces on both sides to indicate two main elements.
const bigCat: Cat = new Cat();
Function names and the opening parenthesis
No space is needed because they mean one thing together.
function getFood(): void
Arguments
Separate with space and comma.
cookDinner(apple, curry, pork);
The precedence of operators
return a*b*c + d%2;
The initial work from the author is not helpful for code readability.
Thus, unaligned declarations and assignments work better.
A source file is a hierarchy rather like an outline
Class
space
Method
space
space
Implementation of the method
space
space
space
Containing block
space
space
space
space
Block implementation
space
space
space
space
space
…
This is bad:
Nice:
The author avoids collapsing scopes down to one line:
More readable:
Difficult to find the end ;
Members of a team should follow the same coding style.
See the example codes of Listing 5-6 CodeAnalyzer.java in the book.
learn
clean code
test automation