Java Reference
In-Depth Information
use; they are less error prone and more secure [EJ Item 13].
To perform a computation on a variable containing a reference to an immutable object, assign the
result of the computation to the variable. Doing this yields the following program, which prints the
expected result of 555000 :
import java.math.BigInteger;
public class BigProblem {
public static void main(String [] args) throws Exception {
BigInteger fiveThousand = new BigInteger("5000");
BigInteger fiftyThousand = new BigInteger("50000");
BigInteger fiveHundredThousand
= new BigInteger("500000");
BigInteger total = BigInteger.ZERO;
total = total.add(fiveThousand);
total = total.add(fiftyThousand);
total = total.add(fiveHundredThousand);
The lesson of this puzzle is: Do not be misled into thinking that immutable types are mutable.
This is a common error among beginning Java programmers. In fairness, the names of some
methods in Java's immutable types help to lead them astray. Names like add , subtract , and negate
suggest that these methods mutate the instance on which they're invoked. Better names would be
plus , minus , and negation .
A lesson for API designers, then, is: When naming methods for immutable types, prefer
prepositions and nouns to verbs. Prepositions are appropriate for methods with parameters and
nouns for parameterless methods. A lesson for language designers is, as in Puzzle 2 , that it might be
worth offering limited support for operator overloading so that arithmetic operators can be made to
Search WWH ::

Custom Search