Curly Braces
What are the most interesting highlights in popular Java code styles?

In spite of the suggestive image above, we don’t want to commence any unnecessary holy wars. When it comes down to coding styles, most choices are pretty arbitrary and depend on personal preference. Yes, even if tab width changes between editors, and spaces tend to be more precise.

If there were such a thing as developer team anthropology, style guidelines would probably be a major part of it.

In this post we will highlight formatting guidelines and different Java coding styles in companies like Google, Twitter, Mozilla, the Java standard and our own teams at Takipi.

Why use guidelines in the first place?

Readability is the main consideration here. It’s almost certain that you will not be the only person to read the code that you write. And the best thing you can do for the next person who reads your code is to stick to conventions.

A consistent style of writing not only helps create good looking code, but also makes it easier to understand. The twitter guidelines specify one exception and we tend to agree, “if the more ‘readable’ variant comes with perils or pitfalls, readability may be sacrificed”.

The full style guides are available right here:

  1. Google Java style guide (there’s another one for Android)
  2. Twitter style guide
  3. Official Java code conventions (New OpenJDK guidelines are available right here)
  4. Mozilla guidelines
  5. Our own guidelines at Takipi

Let’s see what they have in store.

1. Indentation: tabs vs spaces

First, we need to get this off our chests before proceeding. There’s a clear preference for spaces over tabs in the style guides. We’ll not go into pros and cons here and just share the findings:

Google: 2 spaces (android is 4 spaces, and 8 for line wraps)
Twitter: 2 or 4 spaces (for line wraps)
Mozilla: 4 spaces
Java: 4 spaces, tabs must be set at 8 spaces. Both are acceptable.

Perhaps developers who use tabs don’t like writing style guides 😉

Data from Github suggests that around 10-33% of the Java repositories prefer tabs, and the majority use spaces in different formations, preferring 4 spaces over 2. There’s actually a pretty nice module for running this analysis (comparing different languages). BTW, peeking over to other JVM languages like Scala and Clojure, we see almost 100% 2 spaces.

Considering a larger dataset that covered individual commits gave us different results (The convention analysis project, one of the Github data challenge winners), but we can estimate it to be somewhere in-between probably closer to 10%.

(In case you were curious, at Takipi we prefer tabs. We’re not barbarians. Go Richard Hendricks!)

Tabs vs Spaces
Java Tabs vs Spaces – Analyzing popular code conventions (Source: outsideris/popularconvention)

blog_post-banner

2. Line length, wrapping and breaks

Sometimes lines of Java code tend to get long, and the style guides set conventions on when is it appropriate to break or wrap. The general convention is around 80-100 max length

Google: 100 columns
Twitter: Preference towards 100 columns
Mozilla: Appropriate judgement
Java: 80 columns

Of course apart from natural breaks after semicolons, line breaks are used not only when lines get too long but also for logic separation. The general convention is to break after commas, before operators, and use a hint of common sense.

Here’s an example from twitter’s style guide that makes good use of this concept:

This helps separate statements and create a logic where each line of code represents a contained / “atomic” operation. The style guides tend to agree here.

Blank lines also have an important role in the mix, separating logical blocks. The Java standard style guide also has a reference to double line breaks, separating interface and implementation.

3. Variable Naming

Wide agreement across all style guides. FirstLetterUpperCase for class names camelCase for method and variable names, all lower case package names and ALL_CAPS for final static constants.

A common exception for this would be the logger, which we usually define as:

Twitter’s guideline adds another interesting style of including units in variable names:

4. Exception Catch Clauses

Exceptions are a thorny issue. Recently we’ve covered a research that looked into over 600,000 projects on Github and Sourceforge and uncovered some grim truths about non standard use of exceptions. Google’s and Twitter’s style guides reference the infamous empty catch blocks:

Google: No empty catch blocks
Twitter: In other words, don’t swallow exceptions
Mozilla: No reference
Java: No reference

Moreover, another guideline we recommend to at least try to keep is making sure your exceptions are actionable, and avoid control flow exceptions. The amount of noise so called “normal” exceptions cause in a production environment is terrifying.

The current state of exceptions and error handling, relying mostly on log files to get to their root cause in production, is our main motivation behind building Takipi. If you haven’t already, check it out! We’d love to hear what you think.

5. Parentheses for clarity, and curly braces

Even when they’re not necessary, parentheses can help improve readability. With compound predicates, it’s common to use parentheses for clarity, even when the order of execution is obvious. For example:

So what do the style guides say about grouping parentheses?

Google: “Recommended”
Twitter: “Be explicit” (even when it’s obvious)
Java: “Generally a good idea”
Mozilla: Following the Java standard

When dealing with curly braces, all style guides examined support breaking after the opening brace. At Takipi, we actually do the opposite, but we’re not alone, while the “inline” curly brace is used by the majority of Java developers, 37% of code commits examined here use a new line:

Curly Braces
Block statement styles – Analyzing popular code conventions (Source: outsideris/popularconvention)

6. No Brains Inside Constructors

One guideline that we keep and didn’t find in any of the style guides is not to keep any “brains” inside constructors (so they’re safe from zombies – but not from weak jokes apparently).

If we need to create an object and do some heavy duty operations to build it, we use a creator method instead. For example:

Final Thoughts

There are many more style guidelines that we didn’t cover in this post to avoid making this an exhaustive list, and they’re all available in the original docs linked at the beginning of the post. Readability is a major factor in keeping your code error free, and… it just feels right to keep these OCD senses from tingling.

What are some of the unique guidelines / quirks that you follow? Does your company / team use a style guide of your own? Please feel free to share those in the comments section below!

Yoda

Join over 30,254 Java developers

Get new posts about Java, Scala and everything in between

Watch a live demo
Yoda
Some kind of monster @ OverOps, GDG Haifa lead.
  • hueen

    x > y && doSomething();

    • robot

      void doSomething();
      Where is your God now?

      • cjcmd

        void maybeDoSomething();

  • Jakub Spręga

    Great article! Thanks for Twitter best practices, I didn’t know they are published. I have also written my thoughts about code formatting on http://cslysy.github.io/basics/2016/04/12/code_formatting.html

    • http://www.takipi.com/ Alex Zhitnitsky

      Thanks for the link Jakub! We’ll check it out

  • robot

    x > y
    Space before ‘>’ and after it!

  • Gil Megidish

    This is how World War 1 began

  • AlexByrth

    “Shift + Ctrl + F”
    And Let There be Rock !

  • cj

    With the advent of streams, I like to put streaming functions on separate lines and indented. e.g.:
    Arrays.asList(1, 2, 3, 4)
    ____.stream()
    ____.collect(…)
    ____…
    (_ == space, it didn’t indent when I posted)

    • http://xenoterracide.com/ Caleb Cushing

      don’t do this… do Stream.of( 1, 2, 3, 4 )…

      • cj

        Yes, thanks, I keep forgetting to use Stream.of, much better. I’m also trying to use the guava shortcuts more. My point was that looking at code that uses pipeline/stream methods they frequently like to put them all on one big long line and it seems to me that frequently inhibits readability unless it is only a couple of methods with short parameter lists.

        • http://xenoterracide.com/ Caleb Cushing

          yeah of course,

    • An0nym0usC0ward

      That’s a decent thing to do. The ugly and stupid thing is to allign the dots with the opening ( after arras.asList. Suppose you have an already built list named John, and do the streaming on it. Someone coming along and renaming John to Joe instantly messes up all formatting.

  • Christian

    The logger is not an exception in the naming conevention! Usually the upper case naming pattern is used for constants only. The logger is not a constant. Its state can change.

    From Google Java Style Guide:
    > Every constant is a static final field, but not all static final fields are constants. Before choosing constant case, consider whether the field really feels like a constant. For example, if any of that instance’s observable state can change, it is almost certainly not a constant. Merely intending to never mutate the object is generally not enough

    Also see: https://jira.sonarsource.com/browse/SONARJAVA-432

  • Vitor Canova

    What’s the exact argument for someone use spaces? True question. The only difference I see is you need to type more with spaces.

    • http://xenoterracide.com/ Caleb Cushing

      firstly you shouldn’t have to type more (though backspace more) because your editor can usually convert your press of a tab to convert to spaces.

      couple of reasons though. checkstyle a java tool for checking the style of your code doesn’t really support consistent formatting with tabs to the same level as spaces.

      the problem/benefit of tabs is that they can be rendered at a different number of spaces, so you can render an 8 space tab (tabs default) as 4 spaces, or even 2. This becomes a real problem when determining where “break” the eol. Do you go with 80 columns as 8 space tabs? or 80 columns at the 4 space tabs you’ve set to display? also when you wrap a line, if you use more indentation, a double tab is 16 spaces, and go back to the previous question. Really it comes down to no one really finds 8 space tabs readable, but rendering them differently results in all kinds of insanity on continuation lines and where to wrap lines.

      • Vitor Canova

        I like that I can use tabs as 4 spaces and a mate as 8 tabs and the code is the same. But sure we don’t take into account column break.
        Thanks

      • An0nym0usC0ward

        You can always use tabs for indentation – which is what they were meant for – and spaces for alignment. With this convention, no matter how you change the tab size, code will still look orderly.

        Such a mix of spaces and tabs only gets in the way when your coding standard prescribes ASCII art. For example, if breaking a long list of arguments requires you to align the new line at the opening brace, rather that at one or two tabs indentation. Such coding standards are stupid per se – a renaming of a function will mess your entire format, even in files you are not aware of.