0
\$\begingroup\$

In my code I have method which gets users from database with concrete status. And now I have to add new method which gets users from database with list of statuses. I don't know, is it better to create new repository method or reuse existing code.

I created example method "getUsersWithStatuses" which reuse old method "getUsersWithStatus". But, is it good that this method read data from database in loop?

@Transactional(readOnly = true)
public List<UserDTO> getUsersWithStatus(Long locationId, UserDTO.Status status) {
    List<User> userList = userRepository.findByLocationWithStatus(locationId, orderStatus);
    return userMapper.asDTOs(userList);
}

//new functionality
@Transactional(readOnly = true)
public List<UserDTO> getUsersWithStatuses(Long locationId, EnumSet<UserDTO.Status> statuses) {
    List<UserDTO> result = new LinkedList<>();
    statuses.forEach(status -> result.addAll(getUsersWithStatus(locationId, status)));
    return result;
}
\$\endgroup\$
2
\$\begingroup\$

I would say that in your case it is not a good idea because you will execute the same query many times.

However you can change you calls to have the method with a single status calling the one with many satuses.

List<UserDTO> getUsersWithStatus(Long locationId, Status status) {
  return getUserWithStatuses(EnumSet.of(status));
}

List<UserDTO> getUsersWithStatuses(Long locationId, EnumSet<Status> statuses) {
  // SELECT * FROM users WHERE status IN (..)
}
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.