gamelan
Search EarthWeb
CodeGuru | Gamelan | Jars | Wireless | Discussions
Navigate developer.com
Architecture & Design  
Database  
Java
Languages & Tools
Microsoft & .NET
Open Source  
Project Management  
Security  
Techniques  
Voice  
Web Services  
Wireless/Mobile
XML  
Technology Jobs  

   Developer.com Webcasts:
  The Impact of Coding Standards and Code Reviews

  Project Management for the Developer

  Defining Your Own Software Development Methodology

  more Webcasts...




See the Winners!


Developer Jobs

Be a Commerce Partner
Data Center Solutions
Online Education
Phone Cards
Shop Online
Build a Server Rack
Rackmount LCD Monitor
Imprinted Promotions
Cell Phones
Shop
Memory Upgrades
Computer Hardware
Televisions
Disney World Tickets
Online Education

 


Heroes Happen Here Launch Events
Attend the upcoming launch of three powerful new products, take a test drive, meet the teams, and leave with promotional copies of Windows Server 2008, Microsoft SQL Server 2008, and Microsoft Visual Studio 2008. Register here. »

 
Install What You Need with Windows Server 2008
Windows Server 2008 is Microsofts most full-featured server operating system yet, so it's ironic that one of its most exciting new features is an install option that cuts out most of the other features. Paul Rubens explores why a Server Core installation makes a great deal of sense in many instances. »

 
Simplify Big Business IT for Small and Midsize Companies
Windows Small Business Server 2008 and Windows Essential Business Server 2008 deliver all-in-one solutions to help fuel growth for customers and partners. »

 
Q&A with Bob Muglia: Senior VP, Server and Tools Division
Bob Muglia, senior vice president, Server and Tools Division, discusses Microsofts new interoperability principles and the steps the company is taking to increase the openness of its products. »

 
Q&A with Lutz Ziob, GM of Microsoft Learning
Lutz Ziob, the general manager of Microsoft Learning, talks about how IT professionals can become certified heroes within their enterprises by getting trained and certified in Windows Server 2008. »
Developer News -
SaaS Tool Offers Custom Database Development    May 9, 2008
Microsoft’s Automated Agent: Can We Talk?    May 7, 2008
Borland Finally Sells CodeGear    May 7, 2008
Red Hat Heads For The JON 2.0    May 7, 2008
Free Tech Newsletter -

Project Management Guide: Developing a Web Site. Best Practices, Tips and Strategies. Download Exclusive eBook Now.

Good Java Style, Revisited
By Rob Lybarger

Go to page: 1  2  3  4  Next  

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.)

Go to page: 1  2  3  4  Next  


Tools:
Add www.developer.com to your favorites
Add www.developer.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed


Enterprise Java Archives

Work With InterSystems. Not Separate Systems. Rapidly develop and deploy connectable applications.
Whitepaper: Embeddable Content Platform for OEM's
Flash Demo: Learn how IBM Information Server Blade is easy to manage, highly scalable and efficient.
Five Trends for Application Development & Program Management. Download Complimentary Report Now.
Guide to Developing a Web Site. Best Practices, Tips and Strategies. Download Exclusive eBook Now.



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES