Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Effective Java: Programming Language Guide, Exercises of Java Programming

Offering comprehensive descriptions of techniques used by the experts who developed the Java platform, this book reveals what to do - and what not to do - in ...

Typology: Exercises

2021/2022

Uploaded on 08/05/2022

nguyen_99
nguyen_99 🇻🇳

4.2

(80)

1K documents

1 / 180

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Effective Java: Programming Language Guide and more Exercises Java Programming in PDF only on Docsity!

Joshua Bloch

Publisher: Addison Wesley

First Edition June 01, 2001

ISBN: 0-201-31005-8, 272 pages

Are you ready for a concise book packed with insight and wisdom not found elsewhere? Do

you want to gain a deeper understanding of the Java programming language? Do you want to

write code that is clear, correct, robust, and reusable? Look no further! This book will provide

you with these and many other benefits you may not even know you were looking for.

Featuring fifty-seven valuable rules of thumb, Effective Java Programming Language Guide

contains working solutions to the programming challenges most developers encounter each

day. Offering comprehensive descriptions of techniques used by the experts who developed

the Java platform, this book reveals what to do - and what not to do - in order to produce

clear, robust and efficient code.

  • Foreword
  • Preface
  • Acknowledgments.................................................................................................................
  • Chapter 1. Introduction.......................................................................................................
  • Chapter 2. Creating and Destroying Objects
    • Item 1: Consider providing static factory methods instead of constructors
    • Item 2: Enforce the singleton property with a private constructor...................................
    • Item 3: Enforce noninstantiability with a private constructor..........................................
    • Item 4: Avoid creating duplicate objects..........................................................................
    • Item 5: Eliminate obsolete object references
    • Item 6: Avoid finalizers....................................................................................................
  • Chapter 3. Methods Common to All Objects
    • Item 7: Obey the general contract when overriding equals
    • Item 8: Always override hashCode when you override equals
    • Item 9: Always override toString
    • Item 10: Override clone judiciously
    • Item 11: Consider implementing Comparable.................................................................
  • Chapter 4. Classes and Interfaces.....................................................................................
    • Item 12: Minimize the accessibility of classes and members
    • Item 13: Favor immutability
    • Item 14: Favor composition over inheritance
    • Item 15: Design and document for inheritance or else prohibit it....................................
    • Item 16: Prefer interfaces to abstract classes
    • Item 17: Use interfaces only to define types
    • Item 18: Favor static member classes over nonstatic
  • Chapter 5. Substitutes for C Constructs
    • Item 19: Replace structures with classes..........................................................................
    • Item 20: Replace unions with class hierarchies
    • Item 21: Replace enum constructs with classes
    • Item 22: Replace function pointers with classes and interfaces.......................................
  • Chapter 6. Methods............................................................................................................
    • Item 23: Check parameters for validity............................................................................
    • Item 24: Make defensive copies when needed.................................................................
    • Item 25: Design method signatures carefully...................................................................
    • Item 26: Use overloading judiciously
    • Item 27: Return zero-length arrays, not nulls.................................................................
    • Item 28: Write doc comments for all exposed API elements.........................................
  • Chapter 7. General Programming..................................................................................
    • Item 29: Minimize the scope of local variables
    • Item 30: Know and use the libraries...............................................................................
    • Item 31: Avoid float and double if exact answers are required..................................
    • Item 32: Avoid strings where other types are more appropriate
    • Item 33: Beware the performance of string concatenation
    • Item 34: Refer to objects by their interfaces
    • Item 35: Prefer interfaces to reflection...........................................................................
    • Item 36: Use native methods judiciously
    • Item 37: Optimize judiciously........................................................................................
    • Item 38: Adhere to generally accepted naming conventions
  • Chapter 8. Exceptions
    • Item 39:Use exceptions only for exceptional conditions
    • for programming errors Item 40:Use checked exceptions for recoverable conditions and run-time exceptions
    • Item 41:Avoid unnecessary use of checked exceptions
    • Item 42:Favor the use of standard exceptions
    • Item 43: Throw exceptions appropriate to the abstraction
    • Item 44:Document all exceptions thrown by each method
    • Item 45:Include failure-capture information in detail messages
    • Item 46:Strive for </vetbfailure atomicity
    • Item 47:Don't ignore exceptions
  • Chapter 9. Threads
    • Item 48: Synchronize access to shared mutable data
    • Item 49: Avoid excessive synchronization.....................................................................
    • Item 50: Never invoke wait outside a loop
    • Item 51: Don't depend on the thread scheduler
    • Item 52: Document thread safety
    • Item 53: Avoid thread groups.........................................................................................
  • Chapter 10. Serialization
    • Item 54: Implement Serializable judiciously
    • Item 55:Consider using a custom serialized form..........................................................
    • Item 56:Write readObject methods defensively
    • Item 57: Provide a readResolve method when necessary
  • References

Foreword

If a colleague were to say to you, “Spouse of me this night today manufactures the unusual meal in a home. You will join?” three things would likely cross your mind: third, that you had been invited to dinner; second, that English was not your colleague's first language; and first, a good deal of puzzlement.

If you have ever studied a second language yourself and then tried to use it outside the classroom, you know that there are three things you must master: how the language is structured (grammar), how to name things you want to talk about (vocabulary), and the customary and effective ways to say everyday things (usage). Too often only the first two are covered in the classroom, and you find native speakers constantly suppressing their laughter as you try to make yourself understood.

It is much the same with a programming language. You need to understand the core language: is it algorithmic, functional, object-oriented? You need to know the vocabulary: what data structures, operations, and facilities are provided by the standard libraries? And you need to be familiar with the customary and effective ways to structure your code. Books about programming languages often cover only the first two, or discuss usage only spottily. Maybe that's because the first two are in some ways easier to write about. Grammar and vocabulary are properties of the language alone, but usage is characteristic of a community that uses it.

The Java programming language, for example, is object-oriented with single inheritance and supports an imperative (statement-oriented) coding style within each method. The libraries address graphic display support, networking, distributed computing, and security. But how is the language best put to use in practice?

There is another point. Programs, unlike spoken sentences and unlike most books and magazines, are likely to be changed over time. It's typically not enough to produce code that operates effectively and is readily understood by other persons; one must also organize the code so that it is easy to modify. There may be ten ways to write code for some task T. Of those ten ways, seven will be awkward, inefficient, or puzzling. Of the other three, which is most likely to be similar to the code needed for the task T' in next year's software release?

There are numerous books from which you can learn the grammar of the Java Programming Language, including The Java Programming Language by Arnold, Gosling, and Holmes [Arnold00] or The Java Language Specification by Gosling, Joy, yours truly, and Bracha [JLS]. Likewise, there are dozens of books on the libraries and APIs associated with the Java programming language.

This book addresses your third need: customary and effective usage. Joshua Bloch has spent years extending, implementing, and using the Java programming language at Sun Microsystems; he has also read a lot of other people's code, including mine. Here he offers good advice, systematically organized, on how to structure your code so that it works well, so that other people can understand it, so that future modifications and improvements are less

Preface

In 1996 I pulled up stakes and headed west to work for JavaSoft, as it was then known, because it was clear that that was where the action was. In the intervening five years I've served as Java platform libraries architect. I've designed, implemented, and maintained many of the libraries and served as a consultant for many others. Presiding over these libraries as the Java platform matured was a once-in-a-lifetime opportunity. It is no exaggeration to say that I had the privilege to work with some of the great software engineers of our generation. In the process, I learned a lot about the Java programming language—what works, what doesn't, and how to use the language and its libraries to best effect.

This book is my attempt to share my experience with you so that you can imitate my successes while avoiding my failures. I borrowed the format from Scott Meyers's Effective C++ [Meyers98], which consists of fifty items, each conveying one specific rule for improving your programs and designs. I found the format to be singularly effective, and I hope you do too.

In many cases, I took the liberty of illustrating the items with real-world examples from the Java platform libraries. When describing something that could have been done better, I tried to pick on code that I wrote myself, but occasionally I pick on something written by a colleague. I sincerely apologize if, despite my best efforts, I've offended anyone. Negative examples are cited not to cast blame but in the spirit of cooperation, so that all of us can benefit from the experience of those who've gone before.

While this book is not targeted solely at developers of reusable components, it is inevitably colored by my experience writing such components over the past two decades. I naturally think in terms of exported APIs (Application Programming Interfaces), and I encourage you to do likewise. Even if you aren't developing reusable components, thinking in these terms tends to improve the quality of the software you write. Furthermore, it's not uncommon to write a reusable component without knowing it: You write something useful, share it with your buddy across the hall, and before long you have half a dozen users. At this point, you no longer have the flexibility to change the API at will and are thankful for all the effort that you put into designing the API when you first wrote the software.

My focus on API design may seem a bit unnatural to devotees of the new lightweight software development methodologies, such as Extreme Programming [Beck99]. These methodologies emphasize writing the simplest program that could possibly work. If you're using one of these methodologies, you'll find that a focus on API design serves you well in the refactoring process. The fundamental goals of refactoring are the improvement of system structure and the avoidance of code duplication. These goals are impossible to achieve in the absence of well-designed APIs for the components of the system.

No language is perfect, but some are excellent. I have found the Java programming language and its libraries to be immensely conducive to quality and productivity, and a joy to work with. I hope this book captures my enthusiasm and helps make your use of the language more effective and enjoyable.

Joshua Bloch Cupertino, California April 2001

Acknowledgments

I thank Patrick Chan for suggesting that I write this book and for pitching the idea to Lisa Friendly, the series managing editor; Tim Lindholm, the series technical editor; and Mike Hendrickson, executive editor of Addison-Wesley Professional. I thank Lisa, Tim, and Mike for encouraging me to pursue the project and for their superhuman patience and unyielding faith that I would someday write this book.

I thank James Gosling and his original team for giving me something great to write about, and I thank the many Java platform engineers who followed in James's footsteps. In particular, I thank my colleagues in Sun's Java Platform Tools and Libraries Group for their insights, their encouragement, and their support. The team consists of Andrew Bennett, Joe Darcy, Neal Gafter, Iris Garcia, Konstantin Kladko, Ian Little, Mike McCloskey, and Mark Reinhold. Former members include Zhenghua Li, Bill Maddox, and Naveen Sanjeeva.

I thank my manager, Andrew Bennett, and my director, Larry Abrahams, for lending their full and enthusiastic support to this project. I thank Rich Green, the VP of Engineering at Java Software, for providing an environment where engineers are free to think creatively and to publish their work.

I have been blessed with the best team of reviewers imaginable, and I give my sincerest thanks to each of them: Andrew Bennett, Cindy Bloch, Dan Bloch, Beth Bottos, Joe Bowbeer, Gilad Bracha, Mary Campione, Joe Darcy, David Eckhardt, Joe Fialli, Lisa Friendly, James Gosling, Peter Haggar, Brian Kernighan, Konstantin Kladko, Doug Lea, Zhenghua Li, Tim Lindholm, Mike McCloskey, Tim Peierls, Mark Reinhold, Ken Russell, Bill Shannon, Peter Stout, Phil Wadler, and two anonymous reviewers. They made numerous suggestions that led to great improvements in this book and saved me from many embarrassments. Any remaining embarrassments are my responsibility.

Numerous colleagues, inside and outside Sun, participated in technical discussions that improved the quality of this book. Among others, Ben Gomes, Steffen Grarup, Peter Kessler, Richard Roda, John Rose, and David Stoutamire contributed useful insights. A special thanks is due Doug Lea, who served as a sounding board for many of the ideas in this book. Doug has been unfailingly generous with his time and his knowledge.

I thank Julie Dinicola, Jacqui Doucette, Mike Hendrickson, Heather Olszyk, Tracy Russ, and the whole team at Addison-Wesley for their support and professionalism. Even under an impossibly tight schedule, they were always friendly and accommodating.

I thank Guy Steele for writing the foreword. I am honored that he chose to participate in this project.

Finally, I thank my wife, Cindy Bloch, for encouraging and occasionally threatening me to write this book, for reading each item in its raw form, for helping me with Framemaker, for writing the index, and for putting up with me while I wrote.

numbers, which are introduced with the phrase “On my machine,” should be regarded as approximate at best.

For what it's worth, my machine is an aging homebuilt 400 MHz Pentium® II with 128 megabytes of RAM, running Sun's 1.3 release of the Java 2 Standard Edition Software Development Kit (SDK) atop Microsoft Windows NT® 4.0. This SDK includes Sun's Java HotSpot™ Client VM, a state-of-the-art JVM implementation designed for client use.

When discussing features of the Java programming language and its libraries, it is sometimes necessary to refer to specific releases. For brevity, this book uses “engineering version numbers” in preference to official release names. Table 1.1 shows the correspondence between release names and engineering version numbers.

Table 1.1. Java Platform Versions Official Release Name Engineering Version Number JDK 1.1.x / JRE 1.1.x 1. Java 2 Platform, Standard Edition, v 1.2 1. Java 2 Platform, Standard Edition, v 1.3 1. Java 2 Platform, Standard Edition, v 1.4 1.

While features introduced in the 1.4 release are discussed in some items, program examples, with very few exceptions, refrain from using these features. The examples have been tested on releases 1.3. Most, if not all, of them should run without modification on release 1.2.

The examples are reasonably complete, but they favor readability over completeness. They freely use classes from the packages java.util and java.io. In order to compile the examples, you may have to add one or both of these import statements:

import java.util.; import java.io.;

Other boilerplate is similarly omitted. The book's Web site, http://java.sun.com/docs/books/effective, contains an expanded version of each example, which you can compile and run.

For the most part, this book uses technical terms as they are defined in The Java Language Specification, Second Edition [JLS]. A few terms deserve special mention. The language supports four kinds of types: interfaces, classes, arrays, and primitives. The first three are known as reference types. Class instances and arrays are objects; primitive values are not. A class's members consist of its fields, methods, member classes, and member interfaces. A method's signature consists of its name and the types of its formal parameters; the signature does not include the method's return type.

This book uses a few terms differently from the The Java Language Specification. Unlike The Java Language Specification, this book uses inheritance as a synonym for subclassing. Instead of using the term inheritance for interfaces, this book simply states that a class implements an interface or that one interface extends another. To describe the access level that applies when none is specified, this book uses the descriptive term package-private instead of the technically correct term default access [JLS, 6.6.1].

This book uses a few technical terms that are not defined in The Java Language Specification. The term exported API, or simply API, refers to the classes, interfaces, constructors, members, and serialized forms by which a programmer accesses a class, interface, or package. (The term API, which is short for application programming interface, is used in preference to the otherwise preferable term interface to avoid confusion with the language construct of that name.) A programmer who writes a program that uses an API is referred to as a user of the API. A class whose implementation uses an API is a client of the API.

Classes, interfaces, constructors, members, and serialized forms are collectively known as API elements. An exported API consists of the API elements that are accessible outside of the package that defines the API. These are the API elements that any client can use and the author of the API commits to support. Not coincidentally, they are also the elements for which the Javadoc utility generates documentation in its default mode of operation. Loosely speaking, the exported API of a package consists of the public and protected members and constructors of every public class or interface in the package.

dispense these instances repeatedly so as to avoid creating unnecessary duplicate objects. The Boolean.valueOf(boolean) method illustrates this technique: It never creates an object. This technique can greatly improve performance if equivalent objects are requested frequently, especially if these objects are expensive to create.

The ability of static factory methods to return the same object from repeated invocations can also be used to maintain strict control over what instances exist at any given time. There are two reasons to do this. First, it allows a class to guarantee that it is a singleton (Item 2). Second, it allows an immutable class to ensure that no two equal instances exist: a.equals(b) if and only if a==b. If a class makes this guarantee, then its clients can use the == operator instead of the equals(Object) method, which may result in a substantial performance improvement. The typesafe enum pattern, described in Item 21, implements this optimization, and the String.intern method implements it in a limited form.

A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type. This gives you great flexibility in choosing the class of the returned object.

One application of this flexibility is that an API can return objects without making their classes public. Hiding implementation classes in this fashion can lead to a very compact API. This technique lends itself to interface-based frameworks, where interfaces provide natural return types for static factory methods.

For example, the Collections Framework has twenty convenience implementations of its collection interfaces, providing unmodifiable collections, synchronized collections, and the like. The great majority of these implementations are exported via static factory methods in a single, noninstantiable class (java.util.Collections). The classes of the returned objects are all nonpublic.

The Collections Framework API is much smaller than it would be if it had exported twenty separate public classes for the convenience implementations. It is not just the bulk of the API that is reduced, but the “conceptual weight.” The user knows that the returned object has precisely the API specified by the relevant interface, so there is no need to read additional class documentation. Furthermore, using such a static factory method mandates that the client refer to the returned object by its interface rather than by its implementation class, which is generally a good practice (Item 34).

Not only can the class of an object returned by a public static factory method be nonpublic, but the class can vary from invocation to invocation depending on the values of the parameters to the static factory. Any class that is a subtype of the declared return type is permissible. The class of the returned object can also vary from release to release, for enhanced software maintainability.

The class of the object returned by a static factory method need not even exist at the time the class containing the static factory method is written. Such flexible static factory methods form the basis of service provider frameworks like the Java Cryptography Extension (JCE). A service provider framework is a system wherein providers make multiple implementations of an API available to users of the framework. A mechanism is provided to register these implementations, making them available for use. Clients of the framework use the API without worrying about which implementation they are using.

In the JCE, the system administrator registers an implementation class by editing a well- known Properties file, adding an entry that maps a string key to the corresponding class name. Clients use a static factory method that takes the key as a parameter. The static factory method looks up the Class object in a map initialized from the Properties file and instantiates the class using the Class.newInstance method. The following implementation sketch illustrates this technique:

// Provider framework sketch public abstract class Foo { // Maps String key to corresponding Class object private static Map implementations = null;

// Initializes implementations map the first time it's called private static synchronized void initMapIfNecessary() { if (implementations == null) { implementations = new HashMap();

// Load implementation class names and keys from // Properties file, translate names into Class // objects using Class.forName and store mappings. ... }

}

public static Foo getInstance(String key) { initMapIfNecessary(); Class c = (Class) implementations.get(key); if (c == null) return new DefaultFoo();

try { return (Foo) c.newInstance(); } catch (Exception e) { return new DefaultFoo(); } } }

The main disadvantage of static factory methods is that classes without public or protected constructors cannot be subclassed. The same is true for nonpublic classes returned by public static factories. For example, it is impossible to subclass any of the convenience implementation classes in the Collections Framework. Arguably this can be a blessing in disguise, as it encourages programmers to use composition instead of inheritance (Item 14).

A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods. They do not stand out in API documentation in the way that constructors do. Furthermore, static factory methods represent a deviation from the norm. Thus it can be difficult to figure out from the class documentation how to instantiate a class that provides static factory methods instead of constructors. This disadvantage can be reduced by adhering to standard naming conventions. These conventions are still evolving, but two names for static factory methods are becoming common:

// Singleton with static factory public class Elvis { private static final Elvis INSTANCE = new Elvis();

private Elvis() { ... }

public static Elvis getInstance() { return INSTANCE; }

... // Remainder omitted }

All calls to the static method, Elvis.getInstance, return the same object reference, and no other Elvis instance will ever be created.

The main advantage of the first approach is that the declarations of the members comprising the class make it clear that the class is a singleton: the public static field is final, so the field will always contain the same object reference. There may also be a slight performance advantage to the first approach, but a good JVM implementation should be able to eliminate it by inlining the call to the static factory method in the second approach.

The main advantage of the second approach is that it gives you the flexibility to change your mind about whether the class should be a singleton without changing the API. The static factory method for a singleton returns the sole instance of the class but could easily be modified to return, say, a unique instance for each thread that invokes the method.

On balance, then, it makes sense to use the first approach if you're absolutely sure that the class will forever remain a singleton. Use the second approach if you want to reserve judgment in the matter.

To make a singleton class serializable (Chapter 10), it is not sufficient merely to add implements Serializable to its declaration. To maintain the singleton guarantee, you must also provide a readResolve method (Item 57). Otherwise, each deserialization of a serialized instance will result in the creation of a new instance, leading, in the case of our example, to spurious Elvis sightings. To prevent this, add the following readResolve method to the Elvis class:

// readResolve method to preserve singleton property private Object readResolve() throws ObjectStreamException { /*

  • Return the one true Elvis and let the garbage collector
  • take care of the Elvis impersonator. */ return INSTANCE; }

A unifying theme underlies this Item and Item 21, which describes the typesafe enum pattern. In both cases, private constructors are used in conjunction with public static members to ensure that no new instances of the relevant class are created after it is initialized. In the case of this item, only a single instance of the class is created; in Item 21, one instance is created

for each member of the enumerated type. In the next item (Item 3), this approach is taken one step further: the absence of a public constructor is used to ensure that no instances of a class are ever created.

Item 3: Enforce noninstantiability with a private constructor

Occasionally you'll want to write a class that is just a grouping of static methods and static fields. Such classes have acquired a bad reputation because some people abuse them to write procedural programs in object-oriented languages, but they do have valid uses. They can be used to group related methods on primitive values or arrays, in the manner of java.lang.Math or java.util.Arrays, or to group static methods on objects that implement a particular interface, in the manner of java.util.Collections. They can also be used to group methods on a final class, in lieu of extending the class.

Such utility classes were not designed to be instantiated: An instance would be nonsensical. In the absence of explicit constructors, however, the compiler provides a public, parameterless default constructor. To a user, this constructor is indistinguishable from any other. It is not uncommon to see unintentionally instantiable classes in published APIs.

Attempting to enforce noninstantiability by making a class abstract does not work. The class can be subclassed and the subclass instantiated. Furthermore, it misleads the user into thinking the class was designed for inheritance (Item 15). There is, however, a simple idiom to ensure noninstantiability. A default constructor is generated only if a class contains no explicit constructors, so a class can be made noninstantiable by including a single explicit private constructor :

// Noninstantiable utility class public class UtilityClass {

// Suppress default constructor for noninstantiability private UtilityClass() { // This constructor will never be invoked } ... // Remainder omitted }

Because the explicit constructor is private, it is inaccessible outside of the class. It is thus guaranteed that the class will never be instantiated, assuming the constructor is not invoked from within the class itself. This idiom is mildly counterintuitive, as the constructor is provided expressly so that it cannot be invoked. It is therefore wise to include a comment describing the purpose of the constructor.

As a side effect, this idiom also prevents the class from being subclassed. All constructors must invoke an accessible superclass constructor, explicitly or implicitly, and a subclass would have no accessible constructor to invoke.

Item 4: Avoid creating duplicate objects

It is often appropriate to reuse a single object instead of creating a new functionally equivalent object each time it is needed. Reuse can be both faster and more stylish. An object can always be reused if it is immutable (Item 13).

The isBabyBoomer method unnecessarily creates a new Calendar, TimeZone, and two Date instances each time it is invoked. The version that follows avoids this inefficiency with a static initializer:

class Person { private final Date birthDate;

public Person(Date birthDate) { this.birthDate = birthDate; }

/**

  • The starting and ending dates of the baby boom. */ private static final Date BOOM_START; private static final Date BOOM_END;

static { Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0); BOOM_START = gmtCal.getTime(); gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0); BOOM_END = gmtCal.getTime(); }

public boolean isBabyBoomer() { return birthDate.compareTo(BOOM_START) >= 0 && birthDate.compareTo(BOOM_END) < 0; } }

The improved version of the Person class creates Calendar, TimeZone, and Date instances only once, when it is initialized, instead of creating them every time isBabyBoomer is invoked. This results in significant performance gains if the method is invoked frequently. On my machine, the original version takes 36,000 ms for one million invocations, while the improved version takes 370 ms, which is one hundred times faster. Not only is performance improved, but so is clarity. Changing boomStart and boomEnd from local variables to final static fields makes it clear that these dates are treated as constants, making the code more understandable. In the interest of full disclosure, the savings from this sort of optimization will not always be this dramatic, as Calendar instances are particularly expensive to create.

If the isBabyBoomer method is never invoked, the improved version of the Person class will initialize the BOOM_START and BOOM_END fields unnecessarily. It would be possible to eliminate the unnecessary initializations by lazily initializing these fields (Item 48) the first time the isBabyBoomer method is invoked, but it is not recommended. As is often the case with lazy initialization, it would complicate the implementation and would be unlikely to result in a noticeable performance improvement (Item 37).

In all of the previous examples in this item, it was obvious that the objects in question could be reused because they were immutable. There are other situations where it is less obvious. Consider the case of adapters [Gamma98, p. 139], also known as views. An adapter is one object that delegates to a backing object, providing an alternative interface to the backing

object. Because an adapter has no state beyond that of its backing object, there's no need to create more than one instance of a given adapter to a given object.

For example, the keySet method of the Map interface returns a Set view of the Map object, consisting of all the keys in the map. Naively, it would seem that every call to keySet would have to create a new Set instance, but every call to keySet on a given Map object may return the same Set instance. Although the returned Set instance is typically mutable, all of the returned objects are functionally identical: When one returned object changes, so do all the others because they're all backed by the same Map instance.

This item should not be misconstrued to imply that object creation is expensive and should be avoided. On the contrary, the creation and reclamation of small objects whose constructors do little explicit work is cheap, especially on modern JVM implementations. Creating additional objects to enhance the clarity, simplicity, or power of a program is generally a good thing.

Conversely, avoiding object creation by maintaining your own object pool is a bad idea unless the objects in the pool are extremely heavyweight. A prototypical example of an object that does justify an object pool is a database connection. The cost of establishing the connection is sufficiently high that it makes sense to reuse these objects. Generally speaking, however, maintaining your own object pools clutters up your code, increases memory footprint, and harms performance. Modern JVM implementations have highly optimized garbage collectors that easily outperform such object pools on lightweight objects.

The counterpoint to this item is Item 24 on defensive copying. The present item says: “Don't create a new object when you should reuse an existing one,” while Item 32 says: “Don't reuse an existing object when you should create a new one.” Note that the penalty for reusing an object when defensive copying is called for is far greater than the penalty for needlessly creating a duplicate object. Failing to make defensive copies where required can lead to insidious bugs and security holes; creating objects unnecessarily merely affects style and performance.

Item 5: Eliminate obsolete object references

When you switch from a language with manual memory management, such as C or C++, to a garbage-collected language, your job as a programmer is made much easier by the fact that your objects are automatically reclaimed when you're through with them. It seems almost like magic when you first experience it. It can easily lead to the impression that you don't have to think about memory management, but this isn't quite true.

Consider the following simple stack implementation:

// Can you spot the "memory leak"? public class Stack { private Object[] elements; private int size = 0;

public Stack(int initialCapacity) { this.elements = new Object[initialCapacity]; }