2
\$\begingroup\$

I have the following code block which I'd like to refactor into a method, I just don't see a good way to get the following code into a method which doesn't have multiple responsibilities. Here is the code block:

int maxResults = pageable.getMaxResults(userPrefs);
int firstResult;

if (pageData.isLastPage()) {
    int count = getCountFromDb(); //'Heavy' cost associated with this, so we only 
                                  //determine the count if they are on the last page...
    firstResult = getFirstResult(count, maxResults);
    if (count > 0) {
        boolean isFinalPageFull = (count % maxResults) == 0;
        int pageNum = count / maxResults;
        pageData.setPageNumber((isFinalPage) ? pageNum - 1 : pageNum;
    }
} else {
    firstResult = maxResults * pageNumber;
}

I'd like to move this out into a method or two, but I need to only do this count one time. This limitation is clouding my vision, as I can't think of any function which follows the Single Responsibility Principle. Anything I can do to achieve my goal?

\$\endgroup\$
  • \$\begingroup\$ How do you know you're on the last page without knowing how many total results you have? \$\endgroup\$ – David Harkness Jun 22 '11 at 22:37
  • \$\begingroup\$ It's not the ideal solution, but we send in Integer.MAX_VALUE, then we determine which results & how many should have been displayed on the page. When that occurs we reset the page number on the pageData object as you see, so that we can properly move to the next to last page. I don't like it, but it's what our customer agreed to due to the large tables we work with. \$\endgroup\$ – Scott Jun 23 '11 at 11:11
4
\$\begingroup\$

You could make count a field, then have a function to determineFirstResult(). Then the setPageNumber block can be separated out.

if (pageData.isLastPage()) {
    count = getCountFromDb();
    if (count > 0) {
        boolean isFinalPageFull = (count % maxResults) == 0;
        int pageNum = count / maxResults;
        pageData.setPageNumber((isFinalPage) ? pageNum - 1 : pageNum;
    }
}
firstResult = determineFirstResult();

...

int determineFirstResult(int maxResults) {
    if (pageData.isLastPage()) return getFirstResult(count, maxResults);
    return maxResults * pageNumber;
}

But now you've got a dependency; count has to be determined before calling determineFirstResult() as written. So maybe make count a lazy-loaded field; if it's requested and null, then (and only then) do you getCountFromDb.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.