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

6

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

  

RuboCop :: Cop :: Style :: FinalNewLine
  This cop reinforces the presence of a blank final line in each source file. (adapted from RubyDoc)

In addition to linters , even Git, when running git diff , indicates when there is no blank line at the end of the code 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? Is there a difference in putting a blank line at the end of my code and not putting it?

    
asked by anonymous 28.01.2018 / 21:35

1 answer

3

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

  

A string of 0 or more characters as long as it is not the newline character ending with a newline 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 non-POSIX compliant systems files are usually not terminated with a new line.

Another utility of this standard defined by the IEEE is that when using the shortcut to go to the end of the file in the VSCode, if the last line is large the course will be positioned in the last character of this line if there is a blank line at the end of the file the cursor will position itself in the same one, being able to still visualize the other existing lines without having to use the horizontal scroll bar to return to the beginning of the line.     

29.01.2018 / 00:12