Continuing our series on formatting we will first address the concept of vertical formatting.
File Size
How many lines of code should a file have? This is a question that people can start a very “interesting” conversation. Some people prefer very short files while others have no problem with files that have more than a thousand lines. My opinion is that shorter is better, with lines of code in the lower hundreds. Some people’s brains have no problem with big files but that isn’t my case. Big files can get overwhelming quickly. Also, if a class starts getting very large that probably means that it’s doing more than one thing and should be split up.
The Newspaper Metaphor
Code should tell a story the same way a newspaper article is written. It should start with a headline that lets you know if it’s something you want to read. The first paragraph tells you the general idea of the story and the rest of the article will give you the details if you decide to keep on reading. A source code file should read the same way. You have the constructor, public fields and methods at the top. The private fields and methods that have all the low level details of how things are actually done are closer to the bottom of the file if you want to look at them.
Use vertical spaces to separate concepts
Lines of code that aren’t logically related should be visually separated. The separation between them should be an empty line. This way the different parts that compose the class will be evident, allowing you to easily identify the parts you want to read.
Keep related code together
The same way that concepts should be separated using blank lines, code that is related should be kept in the same block. Breaking up the code with unnecessary blank lines or comments will make reading more difficult.
- Variables should be declared as close as possible to the code that actually uses them.
- Instance Variables should be kept together and put at the beginning of the file.
- If a function depends on other functions, they should be vertically close if possible, going from the highest level of abstraction to the lowest.
In our next post, we will talk about horizontal formatting.