In this article I explain why I’ve grown to accept trailing commas in code. Consider the following two examples:
$characters = [
$characters = [
Which one looks neater?
Personally I think B is neater. It’s also grammatically correct. The list does not continue after ‘Garak’. I’ve coded arrays like this for years.
The JSON specification gave me added justification. Strict JSON does not allow trailing commas. This was for browser compatibility reasons. It’s also faster to parse.
But recently I’ve been persuaded to let it go (🎶). Apart from being prettier (to me) B has no practical advantage over A. And yet A has one massive practical advantage: diffs.
The image above demonstrates how much cleaner visual diffs are when using trailing commas. Because the end of the list is left trailing, you are always simply appending items (a single operation) rather than appending and amending the penultimate item (two operations).
So for the last six months, I’ve been using trailing commas. It’s taken a while to undo ten years of habit — but I’m happy. It makes other developers that prefer A happy too. And they can justify their preference whereas I can’t (pretty is not a good enough reason).
However, there’s been one niggling doubt. Trailing commas in argument lists are not allowed (in PHP anyway). And this is an inconsistency. A list is a list. If it’s allowed in an array, it should be allowed in an argument list. I suppose one could argue that an array is mutable whereas the argument list of a function is immutable. But it causes the same issue as explained with the diffs above (if the function signature changes) and it’s annoying when you forget what type of list you’re working on — this happens a lot when copy-pasting/refactoring.
However with the advent of PHP 7.3 trailing commas in argument lists will be supported. Which is something I support. I wouldn’t have six months ago.