Formatting – Horizontal Formatting

What is the maximum length for a line of code? A long time ago, monitors were only capable of showing only 80 characters per line so that was the limit. Currently, with widescreen monitors and small fonts you can have lines that are definitely way too long. According to the book clean code, most lines of code tend to be around 40 characters and the maximum lines should be around 100 – 120 characters.

Long lines of code have the same problem that very long sentences have. When sentences run long, it shows that the writer is trying to say too much. Sentences should be short and clear, and so should lines of code.

Horizontal spacing

In a line of code, things that are closely related should be close. Things that are not closely related should have spaces that make the logical separation clear. If you’re writing an assignment operation, putting a space before and after the equal operator, will make it easier to see the components of the operation, and the operation being applied.

firstVariable=secondVariable;

firstVariable = secondVariable;

The second line is cleaner, your can intuitively see that there are two variables and one is being copied to the other. In the first line you have to read the whole chunk of text to see the assignment operator in the middle.

If you use an IDE to code, most modern ones will automatically apply spacing to lines of code when you finish writing them.

Indentation

Books have chapters, chapters have sections, sections may have sub sections and so on. Code has indentation levels. Indentation is used to show the scope of the code. The deeper the level of indentation a block of code has, the smaller the scope. Indentation makes code easier to read, you can stay at a larger scope if you only want to get a general idea of what the code does, and go deeper if you want to know more details.

Tabs or spaces? I won’t go there!

 

Leave a Reply