Chapter 7. General Programming
Item 29: Minimize the scope of local variablesThe most powerful technique for minimizing the scope of a local variable is to declare it where it is first used.Nearly every local variable declaration should contain an initializer.
Keep methods small and focused.
The
for loop allows you to declareloop variables, limiting their scope to
the exact region where they're needed. (This region consists of the
body of the loop as well as the initialization, test, and update
preceding the body.) Therefore prefer for loops to while loops.
for (Iterator i = c.iterator(); i.hasNext(); ) {
doSomething(i.next());
}
for (int i = 0, n = expensiveComputation(); i < n; i++) {
doSomething(i);
} Again,
this idiom uses two loop variables, and the second variable, n, is used
to avoid the cost of performing redundant computation on every
iteration. As a rule, you should use this idiom if the loop test
involves a method invocation and the method invocation is guaranteed to
return the same result on each iteration.
Item 30: Know and use the librariesSuppose you want to generate random integers between 0 and some upper bound.
static Random rnd = new Random();
// Common but flawed!
static int random(int n) {
return Math.abs(rnd.nextInt()) % n;
} The
method attempts to map the value returned by rnd.nextInt() into a
nonnegative integer with Math.abs. If nextInt() returns
Integer.MIN_VALUE, Math.abs will also return Integer.MIN_VALUE, and the
remainder operator (%) will return a negative number. Use
Random.nextInt(int) instead.
By using a standard library, you take advantage of the knowledge of the experts who wrote it and the experience of
those who used it before you.
Numerous features are added to the libraries in every major release, and it pays to keep abreast of these additions.
Every programmer should be familiar with the contents of
java.lang,
java.util, and, to a lesser extent,
java.io.
In the 1.2 release, a
Collections Framework was added to the
java.util package. It should be part of every programmer's basic toolkit.
A third-party library worthy of note is Doug Lea's
util.concurrent, which provides high-level concurrency utilities to simplify the task of multithreaded programming.
There are many additions to the libraries in the 1.4 release. Notable additions include the following:
•
java.util.regex— A full-blown Perl-like regular expression facility.
•
java.util.prefs— A facility for the persistent storage of user preferences and program configuration data.
•
java.nio—
A high-performance I/O facility, including scalable I/O (akin to the
Unix poll call) and memory-mapped I/O (akin to the Unix mmap call).
•
java.util.LinkedHashSet,
LinkedHashMap,
IdentityHashMap— New collection implementations.
Item 31: Avoid float and double if exact answers are requiredThe
float and double types are particularly ill-suited for monetary
calculations because it is impossible to represent 0.1 (or any other
negative power of ten) as a float or double exactly.For
example, suppose you have a dollar in your pocket, and you see a shelf
with a row of delicious candies priced at 10, 20, 30, and so forth, up
to a dollar.
// Broken - uses floating point for monetary calculation!
public static void main(String[] args) {
double funds = 1.00;
int itemsBought = 0;
for (double price = .10; funds >= price; price += .10) {
funds -= price;
itemsBought++;
}
System.out.println(itemsBought + " items bought.");
System.out.println("Change: $" + funds);
} If
you run the program, you'll find that you can afford three pieces of
candy, and you have $0.3999999999999999 left. This is the wrong answer!
The right way to solve this problem is to use BigDecimal, int, or long
for monetary calculations:
public static void main(String[] args) {
final BigDecimal TEN_CENTS = new BigDecimal(".10");
int itemsBought = 0;
BigDecimal funds = new BigDecimal("1.00");
for (BigDecimal price = TEN_CENTS; funds.compareTo(price) >= 0; price = price.add(TEN_CENTS)) {
itemsBought++;
funds = funds.subtract(price);
}
System.out.println(itemsBought + " items bought.");
System.out.println("Money left over: $" + funds);
} An
alternative to using BigDecimal is to use int (don't exceed nine
decimal digits) or long (don't exceed eighteen digits), depending on
the amounts involved, and to keep track of the decimal point yourself:
public static void main(String[] args) {
int itemsBought = 0;
int funds = 100;
for (int price = 10; funds >= price; price += 10) {
itemsBought++;
funds -= price;
}
System.out.println(itemsBought + " items bought.");
System.out.println("Money left over: "+ funds + " cents");
} Item 32: Avoid strings where other types are more appropriateStrings are poor substitutes for other value types. More generally, if there's an appropriate value type, whether
primitive or object reference, you should use it; if there isn't, you should write one.Strings
are poor substitutes for aggregate types. A better approach is simply
to write a class to represent the aggregate, often a private static
member class
Strings are poor substitutes for capabilities.
Occasionally, strings are used to grant access to some functionality,
replace the string with an unforgeable key (sometimes called a
capability).
Item 33: Beware the performance of string concatenationDon't
use the string concatenation operator to combine more than a few
strings unless performance is irrelevant. Use StringBuffer's append
method instead. Alternatively, use a character array, or process the
strings one at a time instead of combining them.
Item 34: Refer to objects by their interfaces
If
appropriate interface types exist, parameters, return values,
variables, and fields should all be declared using interface types.
// Good - uses interface as type
List subscribers = new Vector(); rather than this:
// Bad - uses class as type!
Vector subscribers = new Vector(); If you get into the habit of using interfaces as types, your program will be much more flexible. For example, the first
declaration could be changed to read
List subscribers = new ArrayList(); There
is one caveat: If the original implementation offered some special
functionality not required by the general contract of the interface and
the code depended on that functionality, then it is critical that the
new implementation provide the same functionality. For example, if the
code surrounding the first declaration depended on the fact that Vector
is synchronized,
then it would be incorrect to substitute ArrayList for Vector in the declaration.
It is entirely appropriate to refer to an object by a class rather than an interface if no appropriate interface exists.
For example, it is perfectly appropriate to use a value class as a parameter, variable, field, or return type.
If an object belongs to such a
class-based framework, it is preferable to refer to it by the relevant
base class, which is
typically abstract, rather than by its implementation class.
A
final case in which there is no appropriate interface type is that of
classes that implement an interface but provide extra methods not found
in the interface—for example, LinkedList. Such a class should be used
only to refer to its instances if the program relies on the extra
methods: it should never be used as a parameter type (Item 25).
Item 35: Prefer interfaces to reflection
Reflection comes at a price:
You lose all the benefits of compile-time type checking.
The code required to perform reflective access is clumsy and verbose.
Performance suffers.
As a rule, objects should not be accessed reflectively in normal applications at run time.
You
can obtain many of the benefits of reflection while incurring few of
its costs by using it only in a very limited form. For many programs
that must use a class unavailable at compile time, there exists at
compile time an appropriate interface or superclass by which to refer
to the class (Item 34). If this is the case, you can create instances
reflectively and access them normally via their interface or
superclass. If the appropriate constructor has no parameters, as is
usually the case, then you don't even need to use the java.lang.reflect
package; the Class.newInstance method provides the required
functionality.
// Reflective instantiation with interface access
public static void main(String[] args) {
// Translate the class name into a class object
Class cl = null;
try {
cl = Class.forName(args[0]);
} catch(ClassNotFoundException e) {
System.err.println("Class not found.");
System.exit(1);
}
// Instantiate the class
Set s = null;
try {
s = (Set) cl.newInstance();
} catch(IllegalAccessException e) {
System.err.println("Class not accessible.");
System.exit(1);
} catch(InstantiationException e) {
System.err.println("Class not instantiable.");
System.exit(1);
}
// Exercise the set
s.addAll(Arrays.asList(args).subList(1, args.length-1));
System.out.println(s);
} Item 36: Use native methods judiciously
Think
twice before using native methods. Rarely, if ever, use them for
improved performance. If you must use native methods to access
low-level resources or legacy libraries, use as little native code as
possible and test it thoroughly. A single bug in the native code can
corrupt your entire application.
Item 37: Optimize judiciously
Strive to write good programs rather than fast ones.
Strive to avoid design decisions that limit performance.
Consider the performance consequences of your API design decisions.
It is a very bad idea to warp an API to achieve good performance.
Measure performance before and after each attempted optimization.
Item 38: Adhere to generally accepted naming conventions
Internalize
the standard naming conventions and learn to use them as second nature.
The typographical conventions are straightforward and largely
unambiguous; the grammatical conventions are more complex and looser.
To quote from The Java Language Specification, "These conventions should not be followed slavishly if long-held conventional usage dictates otherwise." Use common sense.