Search code examples
javamethodsfunctional-programmingcode-duplication

How to generalize methods using functional Java


Can we reduce code duplication with these methods with the new java functional paradigm? I tried to pass the function as param. But one has Functional and the other BiFunctional. Unable to make it as from below code {1} & {2} are diff JPA queries with different num of method args. I am honestly new to this and appreciate any help.

public long byId(List<Long> ids) {
    Pageable pageRequest = PageRequest.of(0, 10, Sort.Direction.ASC, "id");
    Page<SomeDAO> currentPage = repository.findByIdIn(ids, pageRequest); // {1}

    long totalRecords = 0;
    while (!currentPage.isEmpty()) {
        pageRequest = pageRequest.next();
        totalRecords += currentPage.getContent().size();
        // some BL
        currentPage = repository.findByIdIn(ids, pageRequest); // {1}
    }
    return totalRecords;
}

public long all() {
    Pageable pageRequest = PageRequest.of(0, 10, Sort.Direction.ASC, "id");
    Page<SomeDAO> currentPage = repository.findAll(pageRequest); // {2}

    long totalRecords = 0;
    while (!currentPage.isEmpty()) {
        pageRequest = pageRequest.next();
        totalRecords += currentPage.getContent().size();
        // some BL
        currentPage = repository.findAll(pageRequest);  // {2}
    }
    return totalRecords;
}

Solution

  • Use Function.

    public long byId(List<Long> ids) {
        return general(pageRequest -> repository.findByIdIn(ids, pageRequest));
    }
    
    public long all() {
        return general(pageRequest -> repository.findAll(pageRequest));
    }
    
    public long general(Function<Pageable, Page<SomeDAO>> find) {
        Pageable pageRequest = PageRequest.of(0, 10, Sort.Direction.ASC, "id");
        Page<SomeDAO> currentPage = find.apply(pageRequest);
    
        long totalRecords = 0;
        while (!currentPage.isEmpty()) {
            pageRequest = pageRequest.next();
            totalRecords += currentPage.getContent().size();
            // some BL
            currentPage = find.apply(pageRequest);
        }
        return totalRecords;
    }