Trailing Commas in Java Arrays and Enums
04 May 2016A lot of Java developers might not know that trailing commas are allowed in Java arrays (see JLS Array Initializers). That means you can do something like this
… or even this, if you want (ref):
I have to admit that the first snippet is the better example for the remaining text.
Benefits
Let let me first explain why this is a good thing. There are two main benefits according to Nik Graf, and although he wrote about JavaScript/ECMAScript, I think they are perfectly applicable to Java:
- Clean diffs
- Easy code manipulation
If this is not immediately clear, please read his article. It’s a good read with visual examples. The gist: code changes and you want to only see the relevant changes in your diff and don’t want to change more than necessary.
In other words and back to example 1 above: If you find another dinosaur that lived in Jurassic, or find out one of them did not actually live there (yes, it’s the Triceratops), you just add or remove a line.
Automated Checks
Nik alsorecommends enforcing this style with linting. In the Java world a lot of people use Checkstyle to make sure that code adheres to their standards, and of course there is a rule for this: ArrayTrailingComma
.
The following is a minimal checkstyle configuration using this setting:
The good thing about this is that it checks multi-line array definitions, so something like the second example is not enforced. I included this snippet, because I don’t use Checkstyle that much, but wanted to find out, whether it works correctly. There is even more usable stuff around this example here.
Is There More?
The title gave it away: You can also use these trailing commas in enum
definitions (see JLS Enum Constants). The code I work with usually contains more enums than multi-line array definitions and I think this is not too uncommon.
I tend to write enums this way:
Same benefits as above, but unfortunately I cannot enforce this using Checkstyle, because I haven’t found the corresponding rule yet.