Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: design pattern for paged results

So there's Iterable and Iterator and List. What do you use if you are trying to provide an interface to other Java code, in order to encapsulate functionality provided by a remote service that returns results in "pages"?

As an example, consider a database or a webpage (e.g. flickr API). After the first retrieval of results, you know the total # of results and the first N results, but you don't know the remaining results until you retrieve the rest.

like image 891
Jason S Avatar asked Dec 27 '10 23:12

Jason S


2 Answers

In your case, given that each element is expensive to retrieve, it probably makes sense to take aggregate results and not iterate directly for each element at remove invocation level.

You could provide one method which returns a List like this:

List<YourClass>  getResults(int offset, int maxResults)

where offset would be the index of the first element you want to start from and maxresults is the maximum number of elements you want to have in the list. You can then iterate on the list to display in your page.

The Java Persistence API also follows the same pattern, the Query interface provides 3 methods that do the above:

setFirstResult()
setMaxResults()
List getResultList()

http://download.oracle.com/javaee/5/api/javax/persistence/Query.html

like image 171
jbx Avatar answered Sep 22 '22 20:09

jbx


I would stay compliant with Iterator interface, and wouldn't introduce new methods (as suggested above). Instead I would use lazy loading in hasElements(), nextElement(), and your class getters.

like image 20
yegor256 Avatar answered Sep 21 '22 20:09

yegor256