63

In my current project, we always insert an 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. It 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 it is needed and why it can be important. So my question is:

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

Pang
  • 9,564
  • 146
  • 81
  • 122
tenshi
  • 26,268
  • 8
  • 76
  • 90
  • 1
    I try to remove them when I see them although eclipse inserts them. I don't think there's a correct answer, just coding style. – LazyCubicleMonkey Jan 15 '11 at 15:18
  • 7
    I can't think of a compelling reason for being upset with them, either. Is this really the biggest worry you have about this project? Congratulations - you're doing ridiculously well. This has all the makings of a good Bike Shed argument. – duffymo Jan 15 '11 at 15:19
  • 2
    @duffymo: I also don't see any compelling reason not to insert comment "This is the end of the file. After this line file ENDS!" at the end of each source file. But it's just useless... there is no reason for this. (And also find it not correct to enforce all developers in the team to do it) – tenshi Jan 15 '11 at 15:29
  • 4
    I am very surprised this is considered important enough to worry about. I would have thought correct, readable code is the only thing checkstyle should be used for. – Peter Lawrey Jan 15 '11 at 15:30
  • I agree - a comment to say that the file is ending is ridiculous. But extra whitespace, an extra line? That's not in the same league of annoying, so your analogy doesn't resonate with me. Sorry, Easy Angel, I think you should take the "Easy" out of your name. You should go look up what a bike shed argument is. You sound like a handful. I'm not sure I'd want you on my team. – duffymo Jan 15 '11 at 18:38
  • @duffymo: sorry, I don't meant to be rude in previous comment, just wanted to show the nature of the problem (probably not very accurate). I actually accepted this and also making it. I just was curious about this and wanted to know "why?". I don't think there is something wrong about this. A long as I don't know the reason, this long comment and simple newline are conceptually similar for me. I don't like to enforce people to do something without explanation. Do you prefer team members that just do what you told them to do without any questions? I was told to make it without any explanation – tenshi Jan 15 '11 at 19:28
  • Nope, I don't want to work with sheep. But I also hate arguing about every bloody thing that comes up. Pick your battles - follow through with the ones that really matter. – duffymo Jan 15 '11 at 19:41
  • @duffymo: btw thanks for the reference to bike shed argument! Can you advise something to deal with it? I had also another annoyance (this time I had success :), and it would be very interesting for me to know you opinion. We generated automatically comments for all set/get methods like "Sets field {@link firstName}" and "Gets field {@link firstName}" respectively. I was against it. Do you think it was worth discussion? And the same question about "default comments": for each class we write bunch of comments like "// constants", "// set/get methods", "// constructors", etc... – tenshi Jan 15 '11 at 20:59
  • I'm not in favor of default comments. Comments ought to add new information that will be a help in figuring out what the code is doing in and why, not parroting back something that's obvious from the code itself. If your coders need these kinds of comments, you need to hire better ones. The only justification I can think of would be some automatic metric checker that flagged a lack of comments. That sounds like something an architecture group would mandate - the kind of people that think they know better but don't actually code anymore. – duffymo Jan 15 '11 at 21:05
  • @duffymo: thanks. So as far as I understand, you also think these comments issues are worth discussion (please, correct me if I'm wrong). I agree with you about new line issue - it's bike shed argument. I think I should think less about this (I almost forgot about it after I checked correspondent checkbox in IDE, but still was curious about it) – tenshi Jan 15 '11 at 21:25
  • I would say that the useless comments argument is more worthy than the extra whitespace issue. – duffymo Jan 15 '11 at 21:27
  • Related to "why add a newline": https://stackoverflow.com/q/5813311/328817 – Sam Nov 12 '19 at 10:45

9 Answers9

41

I think they are trying to ensure every file ends with a trailing newline character. This is different from ending with a blank line, a.k.a. empty newline.

Edit: As @Easy Angel succinctly clarified in the comments: trailing newline = "\n" and blank line = "\n\n"

I think either:

  1. your lead is either mandating that every file ends with a newline character, but its being misinterpreted as mandating that every file end with a blank line (i.e. an empty line that ends in a newline), or else

  2. they are trying to ensure every file ends with a newline character by actually mandating every file end with a blank line (a.k.a. empty line that ends with a newline), thereby ensuring files ends with at least one newline (and possibly redundant additional newline - overkill?).

Unless the editor actually shows newline symbols, its not always clear in some editors that a file:

  1. DOES NOT END a newline at all,
  2. ENDS with a single trailing newline, or
  3. ENDS with a blank newline, i.e. 2 trailing newlines

I think most modern source code editors insert a trailing newline. However, when using older more general editors, I would always try to ensure my source code files (and text files in general) always ended with a trailing newline (which occasionally came out as a blank line/empty newline depending on the editor I was using) because:

  1. when using cat to display the file on the command line, if the file lacked a trailing newline, the next output (like the shell prompt or a visual delimiter a script may output between files) would end up appearing right after the last non-newline character rather than starting on a newline. In general, the trailing newline made files more user- and script- friendly.

  2. I believe some editors (I can't remember any specifics) would automatically insert a trailing newline if the text file lacked one. This would make it appear like the file was modified. It would get confusing if you have a bunch of files open in different windows and then go to close all of them - the editor prompts you to save but you are unsure whether you made "real changes" to the file or its just the auto-inserted newline.

  3. Some tools like diff and some compilers will complain about a missing trailing newline. This is more noise that users and tools may have to deal with.


Edit:

About editors adding newlines and not being able to see whether there's a newline vs blank newline at the end of the file, I just tested Vim, Eclipse, and Emacs (on my Windows system with Cygwin): I opened a new file, typed 'h' 'e' 'l' 'l' 'o' and saved without hitting [ENTER]. I examined each file with od -c -t x1.

  1. Vim did add a trailing newline.
  2. Emacs did add a trailing newline.
  3. Eclipse did NOT add a trailing newline.

But

  1. Vim did NOT allow me to cursor down to a blank line under "hello".
  2. Emacs did allow me to cursor down to a blank line under "hello".
  3. Eclipse did NOT allow me to cursor down to a blank line under "hello".

Interpret as you like.


My personal practice is to try to ensure text files end with a trailing newline. I just feel there's the least surprise to people and tools with this is the case. I wouldn't treat source files any different from text files in this respect.

Google turns up this:

which, as of this edit, show hits that talk about warnings about a missing trailing newline coming from C compilers, svn (because of diff), diff, etc. I feel there's a general expectation that text files (source files included) end with a trailing newline and least surprising (and less noisy) when they tend to be there.

Finally this is interesting:

Sanitizing files with no trailing newline
Text files should have all their lines terminated by newline characters (ie, \n). This is stated by POSIX, that says that a text file is

A file that contains characters organized into zero or more lines.
A line, in turn, is defined as
* A sequence of zero or more non- characters plus a terminating character.


HOWEVER, all that said, this is just my personal practice. I'm happy to share my opinion to anyone that asks, but I don't foist this on anyone. I don't feel this is something worth mandating, like I say here:

While I'm one whose all for consistency, I'm also against micromanaging every bit of style. Having a huge list of coding conventions, particularly when some of them seem arbitrary, is part of what discourages people from following them. I think coding guidelines should be streamlined to the most valuable practices that improve the -ilities. How much is readability, maintainability, performance, etc improved by mandating this practice?

Community
  • 1
  • 1
Bert F
  • 85,407
  • 12
  • 106
  • 123
  • Ah... I think I understand what you mean: trailing newline = \n and blank line = \n\n. I think it's trailing newline (but I will check after the weekend). We are using eclipse and it's configurable there (as other IDEs). And I don't think, that somebody will actually **cat** 600 lines java file (but anyway I will ask about this). And about these other editors... why do they inserting these trailing newlines? (is it only for shell scripts that theoretically someday can be used with **cat**? but we are talking about big java project. I wonder whether it's practical/applicable in respect to java) – tenshi Jan 15 '11 at 17:27
  • @Easy Angel - I don't know why some editors add a trailing newline and some don't. And I wouldn't make style decisions based on the number of lines in my files today. – Bert F Jan 15 '11 at 18:46
  • 1
    I like your strategy about discussing it in code reviews (instead of just enforcing). A lot of small code-style practices are subjective and should be treated as such (but not enforced - enforcing will just raise negative emotions and doesn't bring much value for team) – tenshi Jan 15 '11 at 18:50
31

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?

L. Holanda
  • 4,432
  • 1
  • 36
  • 44
  • 1
    Agree, it is always a pain in the eye to see changes in two lines, when you just added one. Maybe I'm just perfectionist. – Rostislav V Sep 21 '17 at 20:20
  • @rastaman, not only about beingperfectionist. It's all about making life easier. No merge conflicts means less manual intervention. I wrote this 4 years ago bye the time only mentioned CSV/SVN. But even this days where majority of developers are using git, this is still an issue. – L. Holanda Sep 22 '17 at 03:59
  • 1
    The original question asked about Java source files. The last line of a .java file is and will always be an unindented closing curly brace. No edit should ever change this. – David Siegal Nov 26 '19 at 21:17
  • 1
    Not really... How about comments? Not saying is the best thing to do, but comments are legal after the closing bracket. – L. Holanda Nov 27 '19 at 01:03
8

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).

Community
  • 1
  • 1
extraneon
  • 23,575
  • 2
  • 47
  • 51
  • No, we don't use any old software or scripts that can possibly require this. Actually everything works perfectly fine without these empty lines. – tenshi Jan 15 '11 at 15:39
  • Then you don't need it, but it may be the reason such a constraint was introduced in code formatting guidelines. – extraneon Jan 15 '11 at 15:51
  • These guidelines are enforced by one person, and I just have hard time to convince him that this is (as you said) just ghosts of the past and that they actually should be eliminated – tenshi Jan 15 '11 at 16:25
  • It's not just old software. Any tool that processes text files is going to have an additional case to consider if it has to handle non-empty files without a trailing newline. They will be faced with either a line of text that does not have a newline, or a text file that consists of a sequence of lines followed by a not-quite-a-line. Meanwhile, what does Eclipse gain by being more difficult in this way? – user1809090 Apr 21 '14 at 17:40
2

Aside from the already mentioned valid reasons for having a trailing newline character (possible issues with older tools and diff), here is another way to look at it:

Why special-case the last line by not appending a newline character when all other lines in the file have one?

friederbluemle
  • 33,549
  • 14
  • 108
  • 109
2

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

Marcell
  • 973
  • 1
  • 6
  • 13
1

Sometimes your compiler doesn't parse it correctly:

Error: Reached end of file while parsing

Leo Izen
  • 4,165
  • 7
  • 37
  • 56
  • Are you sure you paired all brackets in java file? Normally you see "Error: Reached end of file while parsing" if you have forgot to close brackets. – tenshi Jan 15 '11 at 17:32
0

It is just a coding style. Doesn't hurt or help anything. I would not let it bother you it sounds like it is your teams preference to include and empty line. There is not really a good argument against it other than why does anyone care enough to actually add it to checkstyle?

jzd
  • 23,473
  • 9
  • 54
  • 76
  • 2
    Missing empty line before EoF does hurt. Try editing a file without empty line at the end. Insert a new (another non-empty) line. Use a diff tool, or try to do a SVN merge. Any diff tool will interpret that the last line (before change) has contents changed, while it has not. – L. Holanda Jan 31 '13 at 23:07
0

I have never heard of such a requirement.

In fact, I just confirmed that a Java program will run without any compiler/runtime errors or warnings when there isn't a blank line at the end of the file.

This, as some commenters have said, must be a coding style issue. Unfortunately, I can't suggest why it may be important for there to be a blank line at the end of a file in Java. In fact, it seems entirely pointless to me

chrisbunney
  • 5,819
  • 7
  • 48
  • 67
0

We had to do this for some C++ code as the compiler generated a warning about it, and we had a 'no error or warnings' policy. Maybe the issue lies elsewhere... have you a diffing tool have goes haywire or a merge tool that can't handle it?

It's not a big deal really.

James
  • 9,064
  • 3
  • 31
  • 49
  • I think eclipse and all other modern java IDEs can handle this without any problems. I also thought that this is not a big deal, but when it's enforced with checkstyle, then there should be something bigger about this... – tenshi Jan 15 '11 at 16:10