I would like to propose an enhancement to the Router class. I’ll start by
admitting that I am fairly new to the RESTlets API and to this forum. A
proposal similar to this may have been discussed already, or I may be missing
something in the API that works more like I want.
I like the way the Router class lets me attach a target Resource class, so
that a Resource of the appropriate type is created to handle a given request.
However, I would like to have more control over how those Resource objects are
constructed. The use of a specific constructor method (the 3 arg constructor)
is limiting.
My Resource object needs to have some domain information available. With this
type of construction I have to code into my class how it will obtain that
domain information. Moreover I am limited to using static methods to obtain
that information. I would rather have the ability to construct the Resource
in such a way that it is given what it needs to find that domain information.
I propose that the API define a ResourceFactory interface,
interface ResourceFactory {
public Resource createResource( Context context, Request
request, Response response );
}
and the Router class be given two new attach() methods:
public Route attach( String uriPattern, ResourceFactory
resourceFactory );
public Route attachDefault( ResourceFactory resourceFactory );
The logic of the Router would be the same, but instead of invoking the three
arg constructor on the Resource class, it would invoke the
resourceFactory.createResource() method. This would not do away with the
current attach methods, but be an additional mechanism.
This helps the developer make a clear distinction between the Resource
definition and the way it obtains its domain information. For example, all of
the knowledge of interacting with a persistent repository for the domain
information can be coded in the ResourceFactory and the knowledge of how a
Resource is represented according to the client request is coded in the
Resource class.
Another benefit is that it makes my Resource classes significantly easier to
Unit test. I can easily construct my Resource object giving it mock objects
for its domain.
Regards,
Jon Lachelt