November 26, 2014
Hot Topics:

Good Java Style, Revisited

  • April 16, 2008
  • By Rob Lybarger
  • Send Email »
  • More Articles »

Introduction

I was recently asked to review and update an older article entitled "Good Java Style" which was presented in two parts (Part One and Part Two) by Thornton Rose; it originally ran on this site in 2001. Inasmuch as the landscape of software and the IT industry changes almost daily, I agreed to attempt an updated presentation and maybe add a bit more of the "why" based on my own experiences. Of course, as with any online article, this will not be an exhaustive survey of all Java style considerations, but I do aim to hit all the high points.

Why Style Matters

If you are writing code for a living, you are most likely working with a team of fellow developers, all battling the impossibility of feature requirements on one hand against some looming deadline on the other. The one thing that makes good teams—and breaks bad ones—is communication. Requirements, schedules, test cases, assumptions, algorithms, patterns, those little "fix me" comments: These are the thousands of little details that development staff must juggle to get something that works, as planned, out the door so that money comes back in. Although parts of that list are handled at different levels of the organization, you still must be able to effectively communicate with your fellow development staff.

Many of you probably had a high school writing teacher or college professor who required a certain style for you to follow in their class for term papers, book reports, and such. Colleges and trade organizations also have their own styles for written material (theses, journal articles, and so forth) that must be followed. Even though the logical organization of material might seem arbitrary when a single article is considered, a collection of related works, each with their own arbitrarily applied style, turns into an unusable mess. It is no different with software source code. To clearly and effectively express your thought of "this is what this code does" to other people, it is immensely helpful for everyone to have a consistent set of expectations as to how that source code is presented. Spotting the mistake in a piece of logic that fails just one time out of a hundred can sometimes be impossible to focus on when your mind is instead cluttered with little mental bookmarks about the exact context in which one little source token exists (much less its enclosing method, class, package, and so on). As a case in point: whatallismisspelledinthisentencethathsnospacesinit?

Requoting from the Java Code Conventions:

  • 80% of the lifetime cost of a software product goes to maintenance.
  • Hardly any software is maintained for its whole life by the original author(s).
  • Using good style improves the maintainability of software code.

History Note

As an aside, the preceding reference was last updated in 1999, back when we were just starting to use Java 1.2. As for the initial version of this article written in 2001, Sun had just made Java 1.3 available. We are now, in 2008, using Java 1.6, and there have been a lot of enhancements made to the language, as well as Java's role in the software ecosystem, since. Java 1.7 is even on the drawing board. However, the foregoing statements are still as true now as they ever were.

House Styles and Holy Wars

As has been mentioned above, what is truly king is that you effectively communicate with your colleagues. (In fact, just being able to communicate with yourself after a six-month break can be a good thing, too.) Seasoned software developers tend to be passionate about their preferences and their prejudices, nearly to the point of riding into glorious combat to defend the honor of their bracing style or their choice of text editor. It makes great fodder to tease each other around the lunch table, but in a team environment, communication plays a much more important role than whether the "{" is on the "right line" or not. At this point, your team of developers just needs to agree on a common style to use. (This is all the more true if you are all doing the right thing by peer reviewing each other's code.) So, if it is the case that you are the junior developer at a code shop with an established style, the professional thing to do is use that style. But, if you are shopping around for a good style to agree upon, doing a little reading about why different people and different shops use a particular style can be informative.

With that being said, I am not going to try to sell one particular approach over another unless I've seen evidence warranting me to. Moreover, some of the items that developers previously had to worry over are now being handled automatically by solid IDEs, whose general behaviors for styling, indenting, and formatting have basically attained parity with each other. Also, it may happen that an attempt to force a line or two of code into a particular style actually detracts from the general purpose of communication. I feel that clarity of purpose must win over "styling rules at all costs" approaches, so it is hard to say that any absolute ever truly exists.

The IDE Effect

Integrated Developer Environments (IDEs) for Java have matured a great deal in the past seven years. The leading contenders in the "download for free" corner are Sun's Netbeans IDE and the Eclipse IDE. Both editors offer an excellent "Format" tool that fixes basic style and presentation of source code in addition to intelligent indent handling, parenthesis matching, and code completion. Moreover, good IDEs can even have their exact formatting style tweaked to varying degrees. This means that a lot of the heavy lifting can be done for you as you write the code, and also as a one-button cleanup when you're basically finished. The use of an established Formatter configuration can also be an aid to a development group that wants to standardize on a particular code style in a simple way. (Gone are the days of manually adjusting the whitespace around code tokens to get them to adhere to a common style.) Given the sheer power of options that IDEs now provide you, it is silly in the extreme to continue to eschew them in favor of a more primitive "raw mode" text editor. Still, some people are stuck in their ways.

The Monitor Effect

In addition to solid IDE tools, the desktop monitor has likewise made great strides in physical size (and resolution), allowing more material to be shown on the screen at a time. A common code style consideration involved limiting lines of code to 80 characters, for fear that someone might need to view the material on an 80x25 text console. In all honesty, it is the 21st century now, and in the current age of large, widescreen monitors and mice that scroll horizontally as well as vertically (and the afore-mentioned IDE tools) this 80-character line length limit is becoming an anachronism. Unless you have a distinct need to keep lines short due to some process requirement or tooling limitation (or managerial mandate), I'd cast a bit of a wary eye on this one. Still, IDEs carry an option for where to draw a visual hint, with a default value of "80," and the auto-formatters tend to wrap lines that exceed this length. In this circumstance, fighting the formatter probably isn't worth a great deal of effort, but wearing out your Return and Tab keys just to wrap lines on your own isn't either. So, if an 80-character line just feels overly cramped, and your team can agree on some other limit, see what everyone thinks of 120.

General Guidelines

Tabs vs. Spaces

Whether a Tab character results in a literal '\t' being present in the code file or whether some certain number of space characters is used instead can be a issue that causes a little debate. Most people that have a reason ready say that Tabs should be expanded to space characters. Their justification for this is that a plain text file does not have the notion of "tab stops" stored in it (whereas a word processor document does), so it is hard to know whether an actual '\t' character shifts the line over as many places in two separate tools for two separate people or not. However, if the tabs are expanded to space characters, the same amount of indent is applied for everyone. The choice to do either action is usually a configurable option in any decent code editor. Another point then is how many spaces should represent a Tab. The biggest consensus is to use four (4) spaces each. (People who insist on using literal tab characters while reading in an 80x25 console are a particularly vexing breed.)





Page 1 of 4



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel