132

Trailing whitespace is enough of a problem for programmers that editors like Emacs have special functions that highlight it or get rid of it automatically, and many coding standards require you to eliminate all instances of it. I'm not entirely sure why though. I can think of one practical reason of avoiding unnecessary whitespace, and it is that if people are not careful about avoiding it, then they might change it in between commits, and then we get diffs polluted with seemingly unchanged lines, just because someone removed or added a space.

This already sounds like a pretty good reason to avoid it, but I do want to see if there's more to it than that. So, why is trailing whitespace such a big deal?

EpsilonVector
  • 10,763
  • 10
  • 56
  • 103
  • 34
    Trailing whitespace is indeed commit noise. Can't think of any other reason. – yannis Nov 24 '11 at 18:04
  • 1
    I think it has also to do with the fact that the earliest applications had to deal with a very limited or very expensive memory. – Amine Nov 24 '11 at 18:07
  • 21
    A *good* diff tool should be able to ignore trailing (and leading too, if you want) whitespace. After all, Emacs can do it, why not your diff tools? – FrustratedWithFormsDesigner Nov 24 '11 at 18:11
  • 5
    Navigating to end of string with 'End' button could be messy with lots of trailing whitespace. – Iarek Nov 24 '11 at 18:15
  • 2
    @IaroslavKovtunenko: not if you have a decent editor. – Marjan Venema Nov 24 '11 at 18:59
  • 17
    I think you are asking the question the wrong way. The other way around is : « what are advantages of trailing white spaces ? ». The answer become pretty obvious when asking the right question ;) – deadalnix Nov 24 '11 at 19:23
  • 7
    Maybe you should try programming in [Whitespace](http://en.wikipedia.org/wiki/Whitespace_%28programming_language%29). *8') – Mark Booth Nov 24 '11 at 22:40
  • 2
    Cause it's ugly - @FrustratedWithFormsDesigner - no _good_ diff tool would do that by default – Mr_and_Mrs_D Sep 18 '15 at 13:10
  • 2
    In some programming languages it is more important than others. For example, in JavaScript if you have whitespace at the end of a line in a string (not an ES6 template string) it messes things up. – trysis May 25 '16 at 15:30
  • 1
    I've found that inconsistencies in whitespace can cause Git merge conflicts later down the line. I find it safer to not introduce them at all to prevent this issue. – Stevoisiak Sep 27 '17 at 20:41

8 Answers8

89

Reasons that it's important to me:

  • When I hit the "End" key, I expect the cursor to go to the end of the line (depending what editor I'm using and how it's configured) and I expect to be able to start typing right away. If the cursor gets there and I have to delete 3 or 4 characters, it's annoying. Especially if it's inconsistent throughout the file(s).

  • When I have string literals that span multiple lines, trailing whitespace can make the output string look incorrect when it's used.

While not strictly programming, whitespace can seriously mess up data entry, if there's trailing/leading in a file that will be parsed and used as input to something else. This happens the most when a clean, generated input file gets dirtied by someone editing it in Excel or something and then trailing whitespace (and other formatting issueS) can creep in.

FrustratedWithFormsDesigner
  • 46,105
  • 7
  • 126
  • 176
  • 11
    Point 1 is a problem with your editor, not with the trailing white space. – Marjan Venema Nov 24 '11 at 18:57
  • 44
    @MarjanVenema: Yes, an editor could be designed to go to the last NON-whitespace, but then you'd never *know* about the trailing whitespace (unless it was indicated some other way - also I'd probably find it weird that END doesn't go to end-of-line, which is what I'm used to). Which would be a problem with multi-line string literals. So then the editor would have to know that in a multi-line string literal, END should go to the last character, including whitespace. The editor I'm using is not that clever. – FrustratedWithFormsDesigner Nov 24 '11 at 19:01
  • 1
    Going to the last non-white space character is what I like. And I don't have a problem with multi-line string literals as Delphi (my main language) doesn't support them. However, when I would need to check for that, I'd use hightlighting as most editors will show the trailing whitespace when you highlight one or more lines. An editor that does not hightlight trailing whitespace, or that hightlights beyond the last actual character (white space or otherwise) of a line would get my boot pretty darn quickly... – Marjan Venema Nov 24 '11 at 19:18
  • 3
    I would add selection with mouse is difficult to do without selecting extra spaces and that could matter if it's for a cut paste. Or that it generate noise when commit (eventually confilcts !) for nothing. No very big deal, but a lot of little anoyances. It gives the feeling that the previous dev was lazy and expect you to leave in his/her mess. – deadalnix Nov 24 '11 at 19:20
  • 3
    @MarjanVenema > Sorry, but coding isn't about what you prefers. You may prefers thoses stuffs, and good for you. But you are not alone in the world and other devs have to work with you. So what THEY prefers has to be taken into account. – deadalnix Nov 24 '11 at 19:21
  • 2
    @deadalnix: of course, that's why you need a good editor with options to suit most people's preferences. And therefore point 1 is a problem with the editor and not the trailing white space. – Marjan Venema Nov 24 '11 at 20:30
  • 1
    Point 1 is precisely why I prefer having a particular style of trailing whitespace: blank lines being indented with the code they separate. This allows new code to be inserted immediately without having to indent in. – Xiong Chiamiov Jul 14 '13 at 22:49
  • 1
    Devs who obsess about (inconsequential) things be rewarded (/punished) with having to work with devs of a similar calibre. – rakslice Nov 26 '13 at 23:02
  • 3
    @MarjanVenema Less pedantry, more practicality. Who cares whether it's a shortcoming of the editor? Our tools will always have shortcomings. Learn to deal with them. As Frustrated pointed out, that problem is *hard*. This problem has a simple to implement solution: trim trailing whitespace. I'd rather editor designers/programmers spend time on problems without solutions. – jpmc26 Nov 14 '14 at 19:07
  • It can also make string literals look wrong when you remove trailing whitespace at the end of the line. – Thomas Weller Sep 26 '17 at 07:06
36

I really hate trailing whitespace, but the exact reason is a bit vague.

I guess the origin of that feeling is not in programming, but in the desktop publishing field. Have you ever got a document typed by someone else that needed to be typeset into a publication? In all modern publications, especially when using columns, it is custom to have sentences follow each other sequentially within one paragraph, not starting a new line for each sentence. Well, when there is trailing whitespace, it takes a lot more effort to get it right (lots of search and replace actions that eliminate double spaces, etc...).

Other reasons (in programming), not good reasons, I know, but they bother my subconscious psyche in such aggravating intense manner that they compel me to eliminate it:

  • It takes more storage space than necessary
  • The parser will have to skip an extra character for no good reason when compiling
  • Some editors might add an extra blank line when WordWrap is on and the trailing space doesn't fit

Yes, yes I know! I know, these are junk reasons. I'm not a perfectionist, but... well maybe I am?

The last reason I can think of is inconsistent cursor movement. It feels like the cursor is hanging in thin air at the end of a line, every step to the right may cause it to either drop or to hover further to an unknown extent, it just feels unsteady (like those invisible or disappearing blocks that Super Mario used to jump on).

Probably I can be diagnosed with trailspacefobia?

Louis Somers
  • 661
  • 5
  • 9
  • 1
    Not my field, but it does seem strange to me... what kind of typesetting system is it you use there in desktop publishing, that doesn't ignore trailing/multiple spaces _by default_? I thought the way LaTeX and most programming languages do it was standard everywhere, except in consumer-level WYSIWYG junk. – leftaroundabout Feb 28 '12 at 18:23
  • Adobe InDesign (does that also fall under consumer-level WYSIWYG junk?). It will ignore trailing spaces, yes, but replace all linefeeds with spaces in a paragraph and you'll end up with double spaces (which are not ignored), then an extra replace is needed to eliminate those. – Louis Somers Feb 29 '12 at 14:23
  • "Desktop publishing" is not something you do with a "typesetting system". – rakslice Nov 26 '13 at 23:06
  • “Subconscious psyche” is a bit redundant. Kind of like trailing whitespace. – Guildenstern Aug 18 '20 at 14:12
25

A lot of these answers almost touch on the reason it's bad for me, but basically: It "breaks" text editors. My experience is with vim.

Vim is designed so that common actions map to letters so cleanly that you don't even have to think about what letter or key combination to hit. Various hotkeys allow the cursor to jump around the text so quickly that it takes only a couple keystrokes to get it to wherever you want. Even things like folding blocks of code is fast, since you can hit END or $ to jump to the end of the line, where the cursor should overlap { or } or ( or ) or something - there's no need to break your thought flow to get an idea onto the screen.

But then comes along some trailing whitespace, and the cursor's movements are no longer predictable. Your typing process is being interrupted because something you can't see is affecting where the cursor goes, so you have to break your train of thought to send it where it should be.

Ever notice how annoyed people get when they're really focused on a task and someone interrupts them? Yeah, finding trailing whitespace when it's least expected is exactly like that.

As a sidenote, I've also noticed that people who don't care about trailing whitespace are the ones who use the mouse for navigation, and tend to be slower typists because of it...

Izkata
  • 6,048
  • 6
  • 28
  • 43
  • 2
    As a sidenote, typing speed has got nothing to do with whether you use your mouse for navigation or not. Some navigation is perfectly suitable for a mouse. ;p – Steven Jeuris Nov 26 '11 at 03:26
  • 2
    If you use vim you can quickly remove all trailing whitespace: `%s/ *$//` – Giorgio May 16 '14 at 21:52
  • 1
    @Giorgio I know, but I can't just do it anytime because it counts as a change in version control – Izkata May 16 '14 at 22:49
  • 1
    @izkata: True. I reformat files I have to change before checking them in but this is a lost battle if other developers keep checking in files with trailing whitespace. – Giorgio May 17 '14 at 09:13
  • 1
    That is exactly how I feel -- when using } and { in ViM, and the cursor jumps over an empty line because it has some unseen whitespace in it, that really annoys you. Additionally, trailing whitespace serves no purpose and adds unnecessary diffs in commits. It has a reason git diff marks them in red. But your main point can be extended: People that write unnecessary trailing whitespace are usually the ones that are sloppy in other aspects two -- from my experience, it is a fairly good indicator of bad source code, together with inconsistently formatted code. – hochl Aug 07 '20 at 15:21
21

Surprisingly, the most obvious answer is missing: trailing whitespace can and will produce difficult to find bugs.

The most obvious situation is multiline strings. Python, JavaScript and Bash are few examples of the languages which can be affected by this:

print("Hello\·
····World")

produces:

  File "demo.py", line 1
    print("Hello\
                 ^
SyntaxError: EOL while scanning string literal

which is somehow cryptic and difficult to solve if the editor is not configured to display whitespace characters.

While syntax highlight can help avoiding such cases, it's even easier to not having the issue in the first place by not letting whitespace at the end of the lines. This is why some style checkers will raise a warning when encountering trailing whitespace, and some editors will trim them automatically.

enter image description here

Illustration: syntax highlight can help avoiding trailing whitespace in situations where it can lead to bugs, but don't rely just on it.

Another context, briefly mentioned in a previous answer, is data stored in files.

For instance, CSV files which contain trailing whitespace may cause data inconsistency which is also very difficult to detect: standards-compliant parsers will trim the whitespace (the standard indicates that leading or trailing whitespace is irrelevant, unless delimited with double-quotes), but some parsers may misbehave and keep the whitespace as a part of a value.

Other custom formats may specifically consider that whitespace is the part of the value, leading to consistent but still difficult to debug situations.

Arseni Mourzenko
  • 134,780
  • 31
  • 343
  • 513
16

I recently spent a day looking for a bug that turned out to be an unexpected trailing whitespace in data.

ddyer
  • 4,060
  • 15
  • 18
  • 15
    I think it *is* a bug; code processing human-generated input should discard trailing whitespace, and often leading whitespace should also be discarded. – kevin cline Nov 24 '11 at 19:25
  • 1
    @kevincline - It should be at least. If it's not visible on the screen or on the printout, I don't wanna think about it. – Rook Nov 24 '11 at 23:51
  • 7
    Because you spent a day looking for a bug, trailing whitespaces are a big deal? Please edit your answer to be more general than that. Add some background, argumentation, ... I personally never had trailing whitespace problems, but I don't use that as a conclusion that they aren't a problem either. – Steven Jeuris Nov 25 '11 at 12:26
  • 2
    @Steven Trailing whitespace caused a bug which was difficult to track down. Seems like a good answer to me. You can imagine how some data parsing code could break in that situation. – Will Sheppard Nov 20 '14 at 10:24
  • I removed whitespace at the end of data and now a test fails. You're responsible for that. What's your name? Where shall I send the bill? – Thomas Weller Sep 26 '17 at 07:10
9

Besides the obvious problem that it breaks parsing in certain cases? As another poster has noted it can cause subtle and difficult to trace errors. Whitespace is not always insignificant. In some cases, trailing whitespace can significantly change the meaning of a line of code or data.

In most cases whitespace is there to format the code for human readers. Trailing whitespace may indicate several things including:

  • An incomplete statement;
  • A missing comment;
  • A mistaken edit; or
  • Sloppy editing.

Two of these may result in incorrect funtioning, and another may make it more difficult to comprehend the code.

BillThor
  • 6,232
  • 17
  • 17
8

When I select program source code in order to copy and paste it (or delete it) I find it a bit annoying to see all the irregular extra white space at the end of lines: since I have to read the code while I am selecting it, the trailing white space is an unneeded noise. Example (dots represent the white space):

if (fp)........
{....
    fclose(fp);.
}
else
{.....
    prinft("File is NULL\n");
}..

This example is artificial, but I have seen a lot of code that looks like this.

Giorgio
  • 19,486
  • 16
  • 84
  • 135
5

There are programming languages that are sensitive to end-line whitespace. For example, a TCL script will give an error if there is a whitespace at the end of a line.