javamodel-view-controllercrud-repository

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


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?


Solution

  • 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.