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?
Join the DZone community and get the full member experience.
Join For Free
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.
new post: tabs vs spaces: how they write java in google, twitter and pied piper https://t.co/xlabyhk4o9 pic.twitter.com/h5zzhpz5xo
— takipi (@takipid) july 5, 2016
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:
-
google java style guide (there's another one for android)
-
official java code conventions (new openjdk guidelines are available right here )
-
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! )
java 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:
block 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!
Published at DZone with permission of Alex Zhitnitsky, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments