Best practice for returning a list from a repository in the service layer in Java

388 Views Asked by At

I'm working on a Java project and I'm unsure about the best practice for returning a list from a repository in the service layer. I've come across two different approaches and I'm seeking advice on which one is considered better or more efficient.

Way #1

    public List<SubjectModel> getSubjectList(int codeId) {
        List<SubjectModel> subjList = new ArrayList<>();

        subjList.addAll(subjectRepository.findByCodeId(String.valueOf(codeId)));

        return subjList ;
    }

or way #2


    public List<SubjectModel> getSubjectList(int codeId) {

        return subjectRepository.findByCodeId(String.valueOf(codeId));
    }

I'm unsure if it's necessary to create a separate variable (subjList) in Way #1 or if Way #2, which directly returns the repository result, is more preferable. Are there any advantages or disadvantages to either approach? Which one is considered the best practice in the industry?

2

There are 2 best solutions below

2
Big_Foot1989 On BEST ANSWER

If you don't have any explicit reason why you want to have it in an ArrayList, then there is no need to wrap it additionally. I would go with way #2. The important part for the caller is the signature of the method, which defines List<> as the return type in both cases. way #1 just makes it harder to understand the code, because it's more bloated and everyone reading it would be wondering why you put the result in an ArrayList. If there are any specific reasons, then you should at least add a comment explaining why. But the default way to go would be #2 for me.

0
alalalala On

If you develop a popular product and need to print the number log of SubjectModel in online service?

private List<SubjectModel> getSubjectList(int codeId) {
    List<SubjectModel> subjList = subjectRepository.findByCodeId(String.valueOf(codeId));
    log.info("there is {} SubjectModels", subjList.size())
    return subjList ;
}

But this is not necessary, during the development process, it is fine according to actual needs