Search code examples
javarestmethodsoverriding

How to call part of one method in another in the same class?


I would like to use part of one method in another in the same class in order not to duplicate several lines in my code. The first method is:

protected UserDTO map(UserEntity entity) {
    var result = new UserDTO();
    var userRoles = entity.getRoles().stream()
            .map(RoleEntity::getId)
            .map(String::valueOf)
            .collect(Collectors.toList());
    result.setId(entity.getId().toString());
    result.setLastAccessDate(entity.getLastAccessDate());
    result.setRoles(userRoles);
    if (entity.getEmail() != null) {
        var email = new UserDTO.Email(entity.getEmail(), EMAIL_TYPE);
        result.setEmails(List.of(email));
    }
    return result;
}

The second one is:

 public UserResource updateUser(String id, UserResource updatedUser) {
        var optionalUser = userRepository.findById(Integer.valueOf(updatedUser.getUserName()));
            updatedUser.setRoles(optionalUser.get().getRoles()
                    .stream()
                    .map(RoleEntity::getId)
                    .map(String::valueOf)
                    .collect(Collectors.toList()));
            updatedUser.setLastAccessDate(optionalUser.get().getLastAccessDate());
        var entity = mapToUserEntity(updatedUser);
        userRepository.save(entity);
        return updatedUser;
    }

So, I have duplicate code in both methods:

.getRoles()
.stream()
.map(RoleEntity::getId)
.map(String::valueOf)
.collect(Collectors.toList()));

Could you give me the piece of advice - how can I simplify this without creating additional method which will be called in two methods above?


Solution

  • You have to create a new method. Add it to the UserEntity class and call it something like getRoleIds(). Then it technically won't be an additional method call since you're replacing the existing call to getRoles.

    Ex:

    var userRoles = entity.getRoles().stream()
                .map(RoleEntity::getId)
                .map(String::valueOf)
                .collect(Collectors.toList());
    

    becomes

    var userRoles = entity.getRoleIds();