Java Reference
In-Depth Information
public
void
addHandler(Request request, RequestHandler requestHandler)
{
if
(this.requestHandlers.containsKey(request.getName()))
{
throw
new
RuntimeException("A request handler has "
+ "already been registered for request name "
+ "[" + request.getName() + "]");
}
else
{
this
.requestHandlers.put(request.getName(), requestHandler);
}
}
}
First, declare a
HashMap
(
java.util.HashMap
) to act as the registry for your request
handlers
B
. Next, add a protected method,
getHandler
, to fetch the
Request-
Handler
for a given request
C
. If a
RequestHandler
has not been registered, you
throw a
RuntimeException
(
java.lang.RuntimeException
)
D
, because this happen-
stance represents a programming mistake rather than an issue raised by a user or
external system. Java doesn't require you to declare the
RuntimeException
in the
method's signature, but you can still catch it as an exception. An improvement would
be to add a specific exception to the controller framework (
NoSuitableRequest-
HandlerException
, for example).
Your utility method then returns the appropriate handler to its caller
E
.
The
processRequest
method
F
is the core of the
Controller
class. This method
dispatches the appropriate handler for the request and passes back the handler's
Response
. If an exception bubbles up, it's caught in the
ErrorResponse
class, shown
in listing 3.3.
Finally, check to see whether the name for the handler has been registered
G
, and
throw an exception if it has. Looking at the implementation, note that the signature
passes the request object, but you use only its name. This sort of thing often occurs
when an interface is defined
before
the code is written. One way to avoid overdesigning
an interface is to practice test-driven development (see chapter 5).
G
Listing 3.3
Special response class signaling an error
[...]
public
class
ErrorResponse
implements
Response
{
private
Request originalRequest;
private
Exception originalException;
public
ErrorResponse(Request request, Exception exception)
{
this
.originalRequest = request;
this
.originalException = exception;
}
public
Request getOriginalRequest()
{