Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 6

Item 1: Consider static factory methods instead of

constructors
public static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}
One advantage of static factory methods is that, unlike constructors,
they
have names.
A second advantage of static factory methods is that, unlike
constructors,
they are not required to create a new object each time they’re
invoked.
allows immutable classes (Item 15) to use preconstructed instances, or to
cache
instances as they’re constructed, and
A third advantage of static factory methods is that, unlike
constructors,
they can return an object of any subtype of their return type.

Item 2: Consider a builder when faced with many


constructor
parameters
NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).
calories(100).sodium(35).carbohydrate(27).build();

Item 3: Enforce the singleton property with a private


constructor or an enum type
a single-element enum type is the best way to implement a
singleton.
// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}

Item 4: Enforce noninstantiability with a private


constructor
// Noninstantiable utility class
public class UtilityClass {
// Suppress default constructor for noninstantiability
private UtilityClass() {
throw new AssertionError();
}
... // Remainder omitted
}

Item 5: Avoid creating unnecessary objects


String s = new String("stringette"); // DON'T DO THIS!
// DON'T DO THIS!
public boolean isBabyBoomer() {
// Unnecessary allocation of expensive object
Calendar gmtCal =
Calendar.getInstance(TimeZone.getTimeZone("GMT"));
gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);
Date boomStart = gmtCal.getTime();
gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0);
Date boomEnd = gmtCal.getTime();
return birthDate.compareTo(boomStart) >= 0 &&
birthDate.compareTo(boomEnd) < 0;
}
prefer primitives to boxed primitives, and watch out for
unintentional autoboxing.
There’s a new way to create unnecessary objects in release 1.5. It is called
autoboxing, and it allows the programmer to mix primitive and boxed
primitive
types, boxing and unboxing automatically as needed.

Item 6: Eliminate obsolete object references


public Object pop() {
if (size == 0)
throw new EmptyStackException();
Object result = elements[--size];
elements[size] = null; // Eliminate obsolete reference
return result;
}
whenever a class manages its own memory, the programmer should
be alert for memory leaks.
Another common source of memory leaks is caches.
represent the cache
as a WeakHashMap; entries will be removed automatically after they become
obsolete.
Remember that WeakHashMap is useful only if the desired lifetime of cache
entries is determined by external references to the key, not the value.

A third common source of memory leaks is listeners and other


callbacks
disuse. This can be done by a background thread (perhaps a Timer or
ScheduledThreadPoolExecutor) or as a side effect of adding new entries to the
cache. The LinkedHashMap class facilitates the latter approach with its
removeEldestEntry method. For
more sophisticated caches, you may need to use java.lang.ref directly.
They are typically discovered only as a result of careful code
inspection or with the aid of a debugging tool known as a heap
profiler.

Item 7: Avoid finalizers


you should never do anything time-critical in a finalizer.
never depend on a finalizer to update critical persistent state
There are perhaps two legitimate
uses. One is to act as a “safety net” in case the owner of an object forgets to
call its
explicit termination method. While there’s no guarantee that the finalizer will
be
invoked promptly, it may be better to free the resource late than never, in
those
(hopefully rare) cases when the client fails to call the explicit termination
method.
But the finalizer should log a warning if it finds that the resource has
not been
terminated, as this indicates a bug in the client code, which should be fixed.

It is important to note that “finalizer chaining” is not performed


automatically.
If a class (other than Object) has a finalizer and a subclass overrides it, the
subclass
finalizer must invoke the superclass finalizer manually. You should finalize
the subclass in a try block and invoke the superclass finalizer in the
corresponding
finally block

Item 8: Obey the general contract when overriding equals


The equals method implements an equivalence relation. It is:
• Reflexive: For any non-null reference value x, x.equals(x) must return true.
• Symmetric: For any non-null reference values x and y, x.equals(y) must return
true if and only if y.equals(x) returns true.
• Transitive: For any non-null reference values x, y, z, if x.equals(y) returns
true and y.equals(z) returns true, then x.equals(z) must return true.
• Consistent: For any non-null reference values x and y, multiple invocations
of x.equals(y) consistently return true or consistently return false, provided
no information used in equals comparisons on the objects is modified.
• For any non-null reference value x, x.equals(null) must return false.

1. Use the == operator to check if the argument is a reference to this


object.

2. Use the instanceof operator to check if the argument has the correct
type.

3. Cast the argument to the correct type. Because this cast was
preceded by an
instanceof test, it is guaranteed to succeed.

4. For each “significant” field in the class, check if that field of the
argument
matches the corresponding field of this object.

Item 9: Always override hashCode when you override equals


In conjunction with all hash-based collections, including HashMap, HashSet, and
Hashtable.
The key provision that is violated when you fail to override hashCode
is
the second one: equal objects must have equal hash codes.

Item 10: Always override toString

Item 11: Override clone judiciously


The Cloneable interface was intended as a mixin interface (Item 18) for objects
to
advertise that they permit cloning. Unfortunately, it fails to serve this
purpose. Its
primary flaw is that it lacks a clone method, and Object’s clone method
is protected.

Item 12: Consider implementing Comparable


public interface Comparable<T> {
int compareTo(T t);
}
Compares this object with the specified object for order. Returns a negative
integer,
zero, or a positive integer as this object is less than, equal to, or greater
than the specified object.
it is permitted to throw ClassCastException

Item 13: Minimize the accessibility of classes and


members
make each class or member as inaccessible as possible.
private—The member is accessible only from the top-level class where it is
declared.
• package-private—The member is accessible from any class in the
package
where it is declared. Technically known as default access, this is the access
level
you get if no access modifier is specified.
• protected—The member is accessible from subclasses of the class where
it is
declared (subject to a few restrictions [JLS, 6.6.2]) and from any class in the
package where it is declared.
• public—The member is accessible from anywhere.
Instance fields should never be public
Classes with public mutable fields are not thread-safe.
private static final Thing[] PRIVATE_VALUES = { ... };
public static final List<Thing> VALUES =
Collections.unmodifiableList(Arrays.asList(PRIVATE_VALUES));

Item 14: In public classes, use accessor methods, not


public fields

Item 15: Minimize mutability


An immutable class is simply a class whose instances cannot be modified. All
of
the information contained in each instance is provided when it is created and
is
fixed for the lifetime of the object. The Java platform libraries contain many
immutable classes, including String, the boxed primitive classes, and BigInteger
and BigDecimal.
Don’t provide any methods that modify the object’s state (known as
mutators).
Ensure that the class can’t be extended.
Make all fields final.
Make all fields private.
Ensure exclusive access to any mutable components.
Immutable objects are inherently thread-safe; they require no
synchronization.
immutable objects can be shared freely.
Classes should be immutable unless there’s a very good reason to
make them
mutable.

Item 16: Favor composition over inheritance


In other words, a class B should extend a class A only if an “is-a” relationship
exists between the two classes.

Item 18: Prefer interfaces to abstract classes


Existing classes can be easily retrofitted to implement a new
interface.
Interfaces are ideal for defining mixins. Loosely speaking, a mixin is a
type
that a class can implement in addition to its “primary type” to declare that it
provides
some optional behavior.
Interfaces enable safe, powerful functionality enhancements
DisAdvantages
It is far easier to evolve an abstract class than an interface.
Once an interface is released and widely implemented, it is almost
impossible to change.

Item 19: Use interfaces only to define types


One kind of interface that fails this test is the so-called constant interface.
The constant interface pattern is a poor use of interfaces.

Item 20: Prefer class hierarchies to tagged classes


Occasionally you may run across a class whose instances come in two or
more flavors and contain a tag field indicating the flavor of the instance. For
example, consider this class, which is capable of representing a circle or a
rectangle:

You might also like