Trailing commas: good or bad practice? (TL;DR: it’s bad)

! Warning: this post hasn't been updated in over three years and so may contain out of date information.

bad-commaMany programming languages allowing optional trailing commas when declaring collections of data. Some argue it’s good practice; others (including me) that it’s bad. So why are they allowed, why do some swear by them, and why do I argue against them?

For many languages, the following piece of code is valid:

The final comma isn’t necessary, but it isn’t invalid either. In this article on JavaScript, and this StackOverflow question, people argue that it’s good practice for a number of reasons:

  • It makes the code easier to write and modify,
  • It makes it easier to write code generators,
  • It makes diffs of code changes cleaner and easier to read.

Let’s tackle the first two first: it makes code easier to write. Sounds good, no? Kyle Robinson Young, in the above JavaScript article, makes the claim “Code style is the preference of the author”. And that is where, in my view, the problem lies. That is a selfish attitude. Code style should be geared primarily toward the audience; code should be easy to read as a priority over easy to write. The variable c is easy to write, much easier than customerDetails for example. Which one is easier to read though?

Likewise, when reading code with a trailing comma, one is left wondering: did the author put that there to make it easier to change, did they forget to remove it when refactoring, or is something missing; is it a bug? Without asking the author, and hoping they can remember!, it’s a non-trivial task to determine the answer to that question. I’m not sure if that makes it a code smell, but it’s a pretty crappy thing to do to the reader just to make your life easier as the author.

What about the last one though: it makes diffs of code changes cleaner and easier to read. That’s valid surely? Sure, if you use a command-line diff tool that shows a change like (taken from Kyle’s article):

How many people really work out code changes based on looking at diffs in this form though, when so many visual diff tools exist? Those tools kill this argument dead as they simply show awesome: true changed to awesome: true,.

Further, at least where some languages are concerned, the trailing comma rule isn’t applied consistently across the language. Trailing commas are sometimes allowed, sometimes not. The following line is invalid in C#:

In this case, all the arguments for using trailing commas go out the window as they can’t be used.

Making code easy to write over being easy to read is bad practice. Ergo, using trailing commas is bad practice too.

(The image used in this post is taken from this StackOverflow answer and is used here – edited – without permission).