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?
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.
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.
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.
I don't have enough points to comment but I wanted to say something about @Justin Smith statement that "[vim will go] so far as to add one [newline] whether you put it there or not,".
I just checked vim, and while it does have one, vim does not show the blank newline. If you open the file saved with vim in nano, nano will show that there is a blank newline at the end. So I decided to see what happens if I manually make a new line with vim, and nano showed that there are 2 new lines.
To me this makes sense because its like closing the line before the file ends, like closing all your tags in HTML.
精彩评论