Software Development
A Code Kata: Pagination
Many frameworks provide support for pagination of results that come from a database. However, sometimes we need to implement this fairly common pattern.
Using TDD construct the pagination logic.
- Pages are numbered 1-based – e.g. 1, 2, 3, 4
- The user gets to choose the page size
- There is a default page size of 25
- Depending on the page we’re on, we need to know how many rows to skip in the database
- A default request is assumed to be for page 1
- We call into the pagination logic with – total records in the database, requested page number, requested page size – the latter of these can be blank to mean defaults
- The pagination logic returns page 1 if there are no records at all
- The pagination logic corrects the requested page number to bring it into range, if the selected page is out of range
- The pagination logic returns the definition of the page that the request implies – a page in range with its own number, page size, and number of rows to skip in the database
Example:
- Select defaults when there are ten records – returns “Page 1, Page Size 25, Rows To Skip 0”
- Select page 2 with page size 20 when there are 100 records – returns “Page 2, Page Size 20, Rows To Skip 20”
- Select page 10 with page size 10 when there are 20 records – returns “Page 2, Page Size 10, Rows To Skip 10”
If you solve this, please leave a solution, in a language of your choice, including the tests, in the comments.
Published on Java Code Geeks with permission by Ashley Frieze, partner at our JCG program. See the original article here: A Code Kata: Pagination Opinions expressed by Java Code Geeks contributors are their own. |