Java Reference
In-Depth Information
Simply put spaces around all operators +-* / % =. However, don't put a space
after a unary minus: a - used to negate a single quantity, as in -b. That way, it can
be easily distinguished from a binary minus, as in a Ċ b . Don't put spaces
between a method name and the parentheses, but do put a space after every Java
keyword. That makes it easy to see that the sqrt in Math.sqrt(x) is a method
name, whereas the if in if (x > 0) ș is a keyword.
Q UALITY T IP 4.4: Factor Out Common Code
Suppose you want to find both solutions of the quadratic equation ax 2 + bx + c = 0.
The quadratic formula tells us that the solutions are
b 2
2 a
ɨ b
ɨ 4ac
x 1, 2
=
In Java, there is no analog to the operation, which indicates how to obtain two
solutions simultaneously. Both solutions must be computed separately:
x1 = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
x2 = (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a);
This approach has two problems. First, the computation of Math.sqrt(b * b
- 4 * a * c) is carried out twice, which wastes time. Second, whenever the
same code is replicated, the possibility of a typing error increases. The remedy is
to factor out the common code:
double root = Math.sqrt(b * b - 4 * a * c);
x1 = (-b + root) / (2 * a);
x2 = (-b - root) / (2 * a);
You could go even further and factor out the computation of 2 * a , but the gain
from factoring out very simple computations is too small to warrant the effort.
4.5 Calling Static Methods
In the preceding section, you encountered the Math class, which contains a collection
of helpful methods for carrying out mathematical computations. These methods have
a special form: they are static methods that do not operate on an object.
Search WWH ::




Custom Search