Java Reference
In-Depth Information
From the point of view of complexity the former solution is simpler since it con-
sists of a single class. But the latter solution has several advantages. First, it is
more readable since it declares explicitly that the method can generate an error.
Second, the name of the exception provides further information about what kind
of error has occurred. Exception classes on the one hand introduce complexity,
but on the other hand they can be reused for similar errors, thus providing a
uniform approach throughout the system.
We can further compare the two approaches from the point of view of the error
handler.
In the first case the code must check the return value against the error condition:
Object result # c.method();
if (result ## null ){
// handle error
}
// normal processing
In the second case we have to use the try
-
catch construct:
try {
Object result # c.method();
// normal processing
} catch (MyErrorException exception){
// handle error
}
The main advantage of the latter solution is the separation of the normal
processing code from the error handling code, which are intermingled in the
former solution.
Another great advantage is the compiler enforcement. When exceptions are
declared the programmer is forced to handle them, otherwise the compiler signals
an error. In the former case if the programmer forgets to check the return value
for errors the program can be compiled seamlessly.
Every subclass of Format must implement the three abstract methods
getName() , toString() and parse() .
The FixedPointFormat class represents the fixed point format. The toString()
method simply performs the division of numerator and denominator and uses
the standard Double.toString() method to convert the result into a string.
Likewise the parse() method uses the standard Double.parseDouble() method.
public class FixedPointFormat extends Format {
public String getName() { return "fixed"; }
String toString(Rational number) {
double value # ( double )number.numerator
/ ( double )number.denominator;
String result # Double.toString(value);
if (value<0) result # result ! "-";
return result;
}
Search WWH ::




Custom Search