SKIP THE SHIPPING
Use code NOSHIP during checkout to save 40% on eligible eBooks, now through January 5. Shop now.
Register your product to gain access to bonus material or receive a coupon.
8508F-7
The definitive style guide for writing readable, maintainable Java code
With Essential Java Style, developers finally have a Java style guide that offers detailed patterns for real-world implementation. Using GGD1real code, not abstract discussion, Jeff Langr brings together scores of today's best implementation solutions for the problems every Java developer faces. By standardizing these solutions, developers can build Java programs more quickly, efficiently, and reliably-and above all, make them dramatically easier to maintain.
Langr brings together the most useful ideas from many sources, notably the excellent Smalltalk patterns identified in Kent Beck's Smalltalk Best Practice Patterns (Prentice Hall, ISBN: 0-13-476904-X). The patterns in Essential Java Style cover methods, messages, state, collections, classes, and formatting. Each pattern appears on its own page, with its own name and summary box designed to show exactly which problem is being solved.
Streamline the development processes by using these patterns to eliminate random coding and naming styles that complicate maintenance, overly procedural code that can be difficult to understand, and varying techniques for common operations that are often inefficient.
Essential Java Style will be an invaluable reference for Java developers, managers, and other technical professionals throughout the entire project lifecycle by providing:
Click here for a sample chapter for this book: 0130850861.pdf
1. Behavior—Methods.
Methods. Composed Method. Constructor Method. Constructor Parameter Method. Default Parameter Values. Shortcut Constructor Method. Converter Method. Converter Constructor Method. Query Method. Comparing Method. Reversing Method. Method Object. Parameter Object. Debug Printing Method. Method Comment. Intention-Revealing Method Name. Simple Implementations.
Message. Choosing Message. Decomposing Message. Dispatched Interpretation. Double Dispatch. Mediating Protocol. Super. Extending Super. Modifying Super. Delegation. Simple Delegation. Self-Delegation. Pluggable Method Name. Collecting Parameter.
Instance Variables. Temporary Variables. Common State. Variable State. Explicit Initialization. Lazy Initialization. Default Value Constant. Default Value Method. Constant. Constant Method. Constant Pool. Direct Variable Access. Indirect Variable Access. Getting Method. Setting Method. Collection Accessor Method. Enumeration Method. Enumerated Constants. Boolean Property-Setting Method. Role-Suggesting Instance Variable Name. Temporary Variable. Collecting Temporary Variable. Caching Temporary Variable. Explaining Temporary Variable. Reusing Temporary Variable. Role-Suggesting Temporary Variable Name.
Collection. Array. List. Linked List. Equality Method. Map. Hash Map. Hashing Method. Tree Map. Set. Tree Set. Stack. Collection Operations. isEmpty(). contains(Object)/containsAll(Collection). retainAll(Collection). removeAll(Collection). Concatenation. Enumeration. Reverse Enumeration. Do. Collect. Select/Reject. Detect. Inject Into. Collection Idioms. Duplicate Removing Set. Temporarily Sorted Collection. Queue. Lookup Cache.
Simple Superclass Name. Qualified Subclass Name. Typing Interface Name. Scoping Package Name.
Method Signature. Role-Suggesting Parameter Name. Message Send. Left-Aligning Block. Guard Clause. Conditional Expression. Simple Enumeration Variable Name.
The Class Definer Utility.
Java Optimizations. HotSpot. Big O.
Behavior - Method. Behavior - Message. State. Collections. Classes. Formatting.
Each time I learned a new language, I began to recognize and identify specific things that I was doing over and over in my code. Back in my COBOL days (the early 1980s), these repeated bits of code weren't known by the now-ubiquitous buzzword "patterns," but they were most certainly coding constructs that I was aware of and that I actively reused. Since then I have worked extensively with Pascal, C, C++, Smalltalk, and now Java. The spe-cific constructs may have changed, but the concept of a reusable pattern has remained.
To remember these constructs, I typically would save off snippets of code into small, stand-alone demonstration programs. When I encountered the need for a construct that I had already coded, I searched my directory of code chunks, and hopefully found the one that would work well in my new coding challenge. If I was fortunate, I achieved object nirvana reuse! Organizationally speaking, though, this is a less-than-ideal system, and certainly other developers would have a difficult time finding anything useful in my grab-bag of example programs.
Somewhat sadly, I still use this technique in Java today, with only minor improvements. The better Java IDEs today support the concept of a scratch pad or workspace, something that Smalltalk has had for years. These scratch pads allow you to quickly code and test snippets of code on the fly without requiring you to create a new project, open a new file, type all the supporting code, save the code, and so forth. But in the end it's still a random list of solutions that is of little value to other developers.
With this book, then, I offer an improved solution. I intend to fill a void that most of the innumerable Java books available do not address. I explain neither how the language works nor how to use the class libraries. Instead, I describe low-level coding patterns that describe how to properly write Java code. If used appropriately, these patterns can be used as the standard for building cost-effective, universally maintainable systems.
Coming to Java from Smalltalk, I am already encountering what I have experienced too often before with C++ and other languages:
These practices are unfortunate and only drive up the cost of code maintenance. In comparison, the Smalltalk development community has a very established, embedded culture. This culture promotes standards and practices that you adhere to without the enforcement of a compiler. The benefit of adherence to these standards is considerable, as I no longer need to fig-ure out individual programmer styles in order to effectively understand their code.
My hope is to someday see in the Java community the amount of consistency and clarity for which the Smalltalk community strives. This book is my effort to provide such a basis for clear code communication.
If you are a developer and are not aware of the driving force that patterns have become in the industry, you have probably been sleeping in your cubi-cle. There are dozens of books available on the topic. Design Patterns is the father of all software pattern books. Unfortunately, as buzzwords go, too many things today are expressed in terms of patterns, whether or not it makes sense. "Patterns" is to the late 1990s as "client/server" was to the early 1990s.
The best advantage to using patterns, from my experience, is that you now have a clear means of communicating common design concepts. Used properly, patterns allow you to communicate not just within your work-group, your company, or your industry, but within the entire development community.
Other industries have long adopted patterns and appropriate names for them. Without names for their patterns, architects would have to tell you they were designing "a small, open hall immediately inside the front entrance to the house that will act as a waiting area" instead of just using the word "foyer." For Java development and maintenance to be most cost-effective, the development community similarly needs to adopt a common language of coding patterns.
When hiring a plumber to install a new bathtub, you assume he or she knows how to get it to mesh with your house properly, regardless of whether you use copper plumbing, PVC, or a large bucket to fill your tub. Similarly, a new Java maintenance programmer coming on board should be able to maintain the system by first assuming that the common pattern lan-guage has been used. Once this assumption has been proven correct, the programmer should be able to rapidly look at existing code to determine its intent and structure.
The patterns contained within this book are very specific coding-level patterns. They are generally not subsystem design patterns like those contained in Design Patterns. My main intent (and intent is a key word when considering patterns) is to present a guidebook for a common Java coding style defined in terms of patterns.
Other books on style have a significant shortcoming the styles are not named. For rules to be useful, they must somehow be internalized by all developers involved. Without the benefit of descriptive names, it is difficult to understand and communicate specific rules. (What was rule #121 again?) Essential Java Style, and patterns in general, rectify this by providing a precise set of names for the rules.
Regarding intent, the most important thing to do when you are coding is to ensure that someone else will be able to quickly understand what the heck you were thinking. Too often a maintainer has to try to read the mind of a programmer who may be long gone. Clairvoyance is a good skill to have, but unfortunately it is not prevalent in the software development industry. Comments sometimes help, but more often than not the comments are inaccurate, out of date, or don't add value to what the code already states.
If you follow the patterns in this book, the amount of your code that will need commenting should decrease significantly. While the promise of self-documenting code is rarely fulfilled, these patterns give you the best oppor-tunity to allow your code to declare just what it is doing. If you are writing lots of comments to explain things, then your code is not declaring its intent in a simple fashion and could use some cleaning up.
This emphasis on clean, understandable code is extremely important, because maintenance is the costliest part of a typical development shop. The ability to rapidly fix, amend, or enhance code is one of the chief promises of object-oriented development. The reality will only come when coders learn to express themselves clearly and consistently.
What are these patterns? Are they about style or standards? Or neither?
Style is an imprecise word. The word style connotes flash, panache, coolness. On the opposite end of the spectrum, the word standards connotes stodginess, inflexibility, tedium. Neither term accurately describes the goal of this book, which is why it has a subtitle: Patterns for Implementation. I also think that people only reluctantly buy books on standards, so that was left out of the title completely.
There are few hard-and-fast programming rules. Most of these patterns reflect just one possible solution to recurring implementation questions. So the patterns cannot be absolute standards. Yet the patterns do decide what should be the usual and expected solution to a problem. The preferred solution identified by each pattern is generally the simplest, not the most creative. So this book is not about style in the classic sense either.
What these patterns do is provide guidelines for development and a common language with which to communicate these guidelines. All of the patterns have specific names to assist you in internalizing them. The collection of pattern names is the vocabulary for the pattern language.
This book uses a pattern itself for the naming of its patterns. The bulk of the patterns described are the same as those contained within Smalltalk Best Practice Patterns by Kent Beck. Obviously, there are some key differences between the two languages, but other than syntax, Smalltalk has more in common with Java than either C or C++. Many of the extremely useful concepts presented in Beck's book translate very closely to Java. With generous thanks to Beck, I have reused his set of patterns where applicable.
If you program, read, test, or document Java code, Essential Java Style is for you. It is not intended as a programming primer or a class reference, but some of the patterns contained in it will explain Java concepts where necessary. I assume the reader has some minimal knowledge of Java programming, but the reader does not need to be a Java expert to use this book effectively.
Essential Java Style is especially geared toward team development. The patterns provide a common language for communication of implementation concepts. But even if you are the only one who ever looks at your own code, the patterns within will still help you improve your development efforts.
On a personal basis, I have been exposed to Java for three years, working in depth with the language over the past year. I do not consider myself a Java expert, but I do have considerable experience in various other languages. Clean coding is something I have striven for throughout my career. Code almost never exists in a vacuum someone will be reading or maintaining your code in the future. Unlike a muddled movie, which can be walked out on, some poor soul may have to understand your code, like it or not. If you respect your fellow developer, you will strive for clear code.
Essential Java Style is intended to be a manual of style. To get started, all you really need is a Java toolkit or IDE and this book. The latest JDK can always be downloaded from http://www.javasoft.com.
While I recommend you work with JDK 2 or later, most of the examples in this book will apply to any version of the JDK. The bulk of the chapter on Collections (Chapter 4) is specific to the Collections Framework in JDK 2. For the rest of the patterns, differences in implementation between JDK 1.1 and JDK 2 are highlighted.
You should have a basic knowledge of Java programming, including how to edit, compile, and run Java programs. A modest amount of object-oriented experience is expected. I also assume that you have done some sort of actual development before.
While this book refers to other books on design-level patterns, knowl-edge of those patterns is not necessary. The footnotes list several books that are referred to within the text.
There is no CD-ROM provided with this book. The patterns are short. Demonstrations of the patterns can be typed quickly. As such, I believe you will learn more from typing in the patterns yourself, or applying them to your own work, rather than from executing a test program from a CD.
The core patterns in this book are contained within six chapters:
A final Chapter 7, "Development Example," provides a small example that demonstrates how these patterns might be pieced together in actual soft-ware development. Appendix A presents a discussion of performance issues related to the patterns.
Each pattern starts on a new page to help you quickly locate specific patterns. A summary box is provided at the start of each pattern. The summary heading for COMPOSED METHOD is provided below as an example. After the PATTERN NAME, the specific problem to be solved by the pattern is stated in the form of a question (Answers the Question). The Solution is then briefly stated, and the Category to which the pattern belongs is reinforced. Related Patterns are listed as a jumping off point to other patterns that may be useful.
Answers the Question | How do you divide a class into methods? |
Solution | Create small methods that, each of which accomplishes a single task that is concisely represented by the method name. |
Category | Behavioral |
Related Patterns | Method Comment Intention-Revealing Method Name |
I highly recommend reading all of the patterns first to get a good overview of what is available. However, there is no reason why you cannot open the book randomly and choose a pattern to delve into. Many of the patterns, especially core patterns such as COMPOSED METHOD, refer to other patterns or use them as prerequisites.
At the minimum, you should read Chapter 1, "Behavior Methods," which forms the core of how your classes should be organized. Many of the patterns contained within that chapter are closely coupled; there is a yin-yang relationship between them.
Once you get the feel of a few patterns, go back to your own code and see if the patterns can be applied to make it clearer. The more you implement the patterns in actual code, the easier it should be for you to add new patterns to your mental library.
The ultimate test, though, is not how well you can understand your code, but how well another developer can understand it. Where these patterns are most useful is in a team development environment. If you code for yourself, these patterns may have limited usefulness. In a team environment, though, the patterns should greatly assist your development team in achieving common coding habits. Part of your team's lingua franca is this pattern language.
Most team development environments use reviews for code quality assurance. These can be in the form of simple peer reviews, structured walkthroughs, or inspections. Reviews tend to have the following problems:
I hope that these patterns will play a significant role in expediting and improving your review processes. If you use inspections, the benefit of a common guideline should help in leveling the varied points of view. You should also achieve more consistent and complete results, even if the number of inspectors is limited.
With walkthroughs, if everyone involved is familiar with the patterns, inappropriate solutions are identified more rapidly and are expressed more precisely. The developer getting beat up immediately understands what the problem is and how to fix it. ("You need to refactor processFile()
using COMPOSED METHOD, and apply a GUARD CLAUSE to handle the null exception condition.")
I recommend that you initially use a checklist to make passes against code as you look for places where the patterns can be applied. While there are a great number of patterns, developers and reviewers should be able to internalize them quickly. Many of the patterns should already present familiar concepts, so that your goal becomes more of standardizing according to a single solution and communicating that solution with the appropriate pattern name. The patterns will become second nature as your development efforts begin to standardize around cleaner, more maintainable code.
This book uses many snippets of code to explain its concepts. Code is always presented in a fixed font
, as follows:
public static void main(String args)
When the name of a method()
is referenced within the text, it will similarly appear in a fixed font
.
Usually, code that runs more than a line or two is presented in a separate numbered listing. Each listing number begins with the chapter number and is followed by a sequence number that runs consecutively through the chapter. For example, Listing 3.5 is the fifth listing in Chapter 3.
public int getHoursPerWeek() { (1) if (hoursPerWeek == 0) hoursPerWeek = defaultFullTimeHoursPerWeek; return hoursPerWeek; }
When specific lines of code in a listing are mentioned in the text, they are bracketed. In the listing itself, the line number (e.g., line 1) appears in parenthesized bold italics to the left of the pertinent line of code. As with the listings themselves, line numbers are consecutive throughout the chapter.
Also, a methodName()
referred to within the text will not usually explicitly list its parameter types, unless it is necessary to do so to uniquely identify or explain the method (e.g., methodName(String)
).
A ClassName in the text is capitalized per Java standards. Note that a generic instance of a class, or an English-reference to what the class represents, will appear in lowercase. Thus, I may state, "the Employee class con-tains the terminate()
method" but explain that "an employee can be terminated."
The name of an Essential Java Style pattern will always be in small capitals. Patterns from other texts (Design Patterns, for example), will be capitalized.
Demonstration code often will contain a line-comment followed by ellipses:
// ...
This is used to indicate that portions of code not pertinent to the example have been omitted.
In the preparation of the patterns for this book, the Java Language Specification (JLS), the JDK core packages, and industry-accepted standards have all been taken into account.
I am not inclined to provide a glossary, because they usually appear at the end of a book and are often overlooked. Essential Java Style also assumes you are familiar with basic OO (object-oriented) concepts and terminology. There are few terms unique to this text. Some of the important terms that may be unfamiliar are defined here:
If you have read this far and have decided to purchase Essential Java Style, I offer my thanks. My sincere hope is that you take the patterns to heart and help make the code in this world a little cleaner.