# Externalize to a function

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?

• How do you know you're on the last page without knowing how many total results you have? – David Harkness Jun 22 '11 at 22:37
• 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. – Scott Jun 23 '11 at 11:11

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.