Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the reason for leaving an extra blank line at the end of a code file?

Eclipse and MyEclipse create new Java files with an extra blank line after the last closing brace by default. I think CodeWarrior did the same thing a few years back, and that some people leave such blank lines in their code either by intention or laziness. So, this seems to be at least a moderately widespread behavior.

As a former human language editor -- copy editing newspapers, mostly -- I find that those lines look like sloppiness or accidents, and I can't think of a reason to leave them in source files. I know they don't affect compilation in C-style languages, including Java. Are there benefits to having those lines, and if so, what are they?

like image 220
Pops Avatar asked Mar 08 '10 15:03

Pops


3 Answers

It is historical, relating to common bugs in command line utilities for text processing. There are many programs on a Unix system for processing text, and most of them work on a line by line basis. There may or may not be any common command line tools that misbehave when the last line does not end in a newline, but the phenomenon is historically common enough that other tools started warning about the situation.

Last I checked vim is actually incapable of saving a file that does not end in a newline, going so far as to add one whether you put it there or not.

like image 141
Justin Smith Avatar answered Oct 13 '22 22:10

Justin Smith


AFAIK, it is good practice to have every line ended using newline character, because when the code is parsed, it can be read using one simple function, which will split file into lines according to those newline characters. Without blank line and therefore last line ended with newline, you would lose all characters on that line.

like image 25
Gabriel Ščerbák Avatar answered Oct 13 '22 22:10

Gabriel Ščerbák


This isn't necessarily the historical reason why, but is a good reason, IMO:

It prevents you from forgetting to have a trailing newline at the end of your file. Compilers typically warn about this, and source control systems often will too, and will show the line as changed when you add the newline to get rid of your compiler warning.

In short it reduces the potential for noise and unnecessary SCM diffs.

like image 37
Nathan Kidd Avatar answered Oct 13 '22 22:10

Nathan Kidd