Empty new line at the end of the java source files

2019-03-11 14:20发布

In my current project we always insert empty new line at the end of the java source files. We also enforce this with CheckStyle (with error level).

I was searching for this topic for a long time, but unfortunately I can't find any convincing reason for this. Seems that other developers are pretty indifferent about this because they just checked one checkbox in eclipse formatter and it's done automatically. But I still don't know why is it needed and why is it can be important). So my question is:

Why are empty lines at the end of Java source files need? Is it a current need or a relic of the past and undesirable in current code bases?

9条回答
混吃等死
2楼-- · 2019-03-11 14:42

Have a look at this SO question..

The answer shamelessly stolen from Ralph Rickenbach:

Many older tools misbehave if the last line of data in a text file is not terminated with a newline or carriage return / new line combination. They ignore that line as it is terminated with ^Z (eof) instead.

So I figure it's mostly a ghost of the past. Unfortunately, such ghosts can bite you in the tail if you don't properly exorcise them. (Is your build server old and uses older shell scripts for summaries and such things).

查看更多
混吃等死
3楼-- · 2019-03-11 14:43

Try to cut/paste the whole file. Something bug in checkstyle or eclipse : )

查看更多
乱世女痞
4楼-- · 2019-03-11 14:45

Here is a good reason for having extra line-break at the end:

If you have a file without line-break at the end, next time the file is edited to add another line, most of merge tools will think that the existing line has changed (I'm 90% sure SVN also does).

In the example below, the line containing “last line before edit” does not have the line break. If we try to add a new line “last line after edit”, as we can see both lines 5 and 6 are marked as changed, but actual contents of line 5 in both versions are the same.

Without line-break before EOF

If everyone is following your project lead suggestion, then this would be the result (only line 6 differ from original file). This also avoids misunderstandings during merges.

With line-break before EOF

While this may not look like a big deal, let's say one developer (A) actually meant to change the contents of the last line and another developer (B) added a new line. If not using line-break before EOF, then you have a merge conflict because developer B was forced to also edit the former last line to add a line-break. And... who likes CVS/SVN conflicts?

查看更多
登录 后发表回答