Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Tabs vs Spaces: How They Write Java in Google, Twitter, Mozilla, and Pied Piper

DZone's Guide to

Tabs vs Spaces: How They Write Java in Google, Twitter, Mozilla, and Pied Piper

The biggest war among developers continues to rage on. But where do the giants in technology stand on the issue?

· Java Zone
Free Resource

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

Curly Braces
What are the Most Interesting Highlights in 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 if spaces tend to be more precise.

If there was 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 with conventions.

A consistent style of writing not only helps create good looking code, but also makes the code 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.

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 the pros and cons here and just share the findings:

Google: Two spaces (android is four spaces, and eight for line wraps)
Twitter: Two or four spaces (for line wraps)
Mozilla: Four spaces
Java: Four spaces, tabs must be set at eight spaces. Both are acceptable.

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

Data from Github suggests that around 10-33 percent of the Java repositories prefer tabs, and the majority use spaces in different formations, preferring four spaces over two. There’s actually a pretty nice module for running this analysis (comparing different languages). By the way, peeking over to other JVM languages like Scala and Clojure, we see almost 100 percent two 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 percent.

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

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

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:

// Bad.
//   - Line breaks are arbitrary.
//   - Scanning the code makes it difficult to piece the message together.
throw new IllegalStateException("Failed to process request" + request.getId()
    + " for user " + user.getId() + " query: '" + query.getText()
    + "'");

// Good.
//   - Each component of the message is separate and self-contained.
//   - Adding or removing a component of the message requires minimal reformatting.
throw new IllegalStateException("Failed to process"
    + " request " + request.getId()
    + " for user " + user.getId()
    + " query: '" + query.getText() + "'");

This helps separate statements and create 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.

Variable Naming

Wide agreement across all style guides. FirstLetterUpperCase for class names, CamelCase for method and variable names, and 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:

private static final Logger logger = LoggerFactory.getLogger(Class.class);

Twitter’s guidelines add another interesting style of including units in variable names:

// Bad.
//   - Field names give little insight into what fields are used for.
class User {
  private final int a;
  private final String m;

  ...
}

// Good.
class User {
  private final int ageInYears;
  private final String maidenName;

  ...
}

Exception Catch Clauses

Exceptions are a thorny issue. Recently, we’ve covered a research project 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.

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:

if (x == y && a > 10) // bad
if ((x == y) && (a > 10)) // good

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 percent of code commits examined here use a new line:

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

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:

// simple constructor
//
private final int x;
private final int y;
private final String z;

public MyClass(int x, int y, String z) {
    this.x = x;
    this.y = y;
    this.z = z;
}


// complex building
//
public static MyClass create(List<Stuff> list, Set<Stuff> set) {
    // int x = some brains...
    // int y = more brains...
    // other brains...
    // String z = more complex stuff here
    //
    return new MyClass(x, y, z);
}

private final int x;
private final int y;
private final String z;

private MyClass(int x, int y, String z) {
    this.x = x;
    this.y = y;
    this.z = z;
}

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!

Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.

Topics:
style guides ,java ,exceptions ,coding ,spaces

Published at DZone with permission of Alex Zhitnitsky, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}