Why insert a blank line at the end of the code?

Asked

Viewed 991 times

6

Most linters from different programming languages, such as Rubocop (Ruby) and Jslint (Javascript) recommend a blank line from the end of all code files. As an example, Rubocop:

Rubocop::Cop::Style::Finalnewline
That one Cop reinforces the presence of a blank final line in each source file. (adapted from Rubydoc)

Besides the linters, to Git, when running git diff, indicates when there is no blank line at the end of the source files:

No newline at end of file

To illustrate, the result is:

1 def say_hi
2   puts 'hi'
3 end
4
5 say_hi
6

Is it just a convention? There is a difference in putting a blank line at the end of my code and not putting?

  • 3

    Related to Soen: https://stackoverflow.com/q/2287967/1452488

  • 2

    We also have the Unix influence, where there is always line break at the end of a text file

1 answer

5


According to the POSIX standards defined by the IEEE, a line can be defined as follows::

A sequence of 0 or more characters as long as it is not the new line character ending with a new line character

isso não é considerado uma linha

isso é considerado uma linha\n

When working with standard Unix tools for example, if there is no such line break at the end, some problems may appear.

An example is the concatenation of files using the cat command:

$ more a.txt
texto1$ more b.txt
texto2
$ more c.txt
texto 3
$cat *.txt
texto1texto2
texto3

On systems not compliant with the POSIX standard the files are usually not terminated with a new line.

Another utility of this pattern defined by the IEEE is that when using the shortcut to go to the end of the file in Vscode, if the last line is large the stroke will be in the last character of that line, if there is a blank line at the end of the file the cursor will position itself in it, and you can still view the other existing lines without having to use the horizontal scroll bar to return to the beginning of the line.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.