I have a Spring Boot application and I wrote a piece of code to manage relationships between two entities.
The code consists mostly in these two methods:
@Override
public void associateDocumentsToPersonRecord(Long personRecordId, AssociationDTO associationDTO) {
PersonRecord personRecord = personRecordRepository.findById(personRecordId).orElse(null);
if (personRecord == null)
return;
for (Long documentId : associationDTO.getDocumentsId())
documentRepository
.findById(documentId)
.ifPresent(document -> personRecord.getDocuments().add(document));
personRecordRepository.save(personRecord);
}
@Override
public void removeAssociateDocumentsToPersonRecord(Long personRecordId, AssociationDTO associationDTO) {
PersonRecord personRecord = personRecordRepository.findById(personRecordId).orElse(null);
if (personRecord == null)
return;
for (Long documentId : associationDTO.getDocumentsId())
documentRepository
.findById(documentId)
.ifPresent(document -> personRecord.getDocuments().remove(document));
personRecordRepository.save(personRecord);
}
One method is for adding relations, the other is to remove them.
I definitely get the smell of duplicated code and the only thing that changes is remove
or add
between the two methods.
How could I refactor this code in the most elegant way?