Skip to content

Suggestion: Increases readability of PageableExecutionUtils code #3103

Closed
@erie0210

Description

@erie0210

I noticed PageableExecutionUtils code could potentially benefit from refactoring. I found it too complex due to multiple branches of if statements. I think these adjustments could improve readability of the codebase. I am open to any feedback or suggestions you might have. I would be happy to open a pull request with these changes if needed. Please let me know your thoughts.

Here's the suggested code. All tests passed.

Thank you.

AS_IS

public abstract class PageableExecutionUtils {

	private PageableExecutionUtils() {}

	public static <T> Page<T> getPage(List<T> content, Pageable pageable, LongSupplier totalSupplier) {

		Assert.notNull(content, "Content must not be null");
		Assert.notNull(pageable, "Pageable must not be null");
		Assert.notNull(totalSupplier, "TotalSupplier must not be null");

		if (pageable.isUnpaged() || pageable.getOffset() == 0) {

			if (pageable.isUnpaged() || pageable.getPageSize() > content.size()) {
				return new PageImpl<>(content, pageable, content.size());
			}

			return new PageImpl<>(content, pageable, totalSupplier.getAsLong());
		}

		if (content.size() != 0 && pageable.getPageSize() > content.size()) {
			return new PageImpl<>(content, pageable, pageable.getOffset() + content.size());
		}

		return new PageImpl<>(content, pageable, totalSupplier.getAsLong());
	}
}

TO_BE

public abstract class PageableExecutionUtils {

	private PageableExecutionUtils() {}

	public static <T> Page<T> getPage(List<T> content, Pageable pageable, LongSupplier totalSupplier) {

		Assert.notNull(content, "Content must not be null");
		Assert.notNull(pageable, "Pageable must not be null");
		Assert.notNull(totalSupplier, "TotalSupplier must not be null");

		if (pageable.isUnpaged() || isFirstPageWithLessThanOneFullPage(content, pageable)) {
			return new PageImpl<>(content, pageable, content.size());
		}

		if (isSubsequentPageWithLessThanOneFullPage(content, pageable)) {
			return new PageImpl<>(content, pageable, pageable.getOffset() + content.size());
		}

		return new PageImpl<>(content, pageable, totalSupplier.getAsLong());
	}

	private static <T> boolean isFirstPageWithLessThanOneFullPage(List<T> content, Pageable pageable) {
		return pageable.getOffset() == 0 && pageable.getPageSize() > content.size();
	}

	private static <T> boolean isSubsequentPageWithLessThanOneFullPage(List<T> content, Pageable pageable) {
		return pageable.getOffset() != 0 && !content.isEmpty() && pageable.getPageSize() > content.size();
	}
}

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions