Factor out pagination code