0
\$\begingroup\$

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?

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Mar 7, 2019 at 21:17
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You may extract the action part as a method parameter (I am using BiConsumer in this case).

@Override
public void performActionOnRecords(Long personRecordId, AssociationDTO associationDTO, BiConsumer<PersonRecord,Document> action) {
 PersonRecord personRecord = personRecordRepository.findById(personRecordId).orElse(null);
 if (personRecord == null)
 return;
 for (Long documentId : associationDTO.getDocumentsId())
 documentRepository
 .findById(documentId)
 .ifPresent(document -> action.accept(personRecord,document));
 personRecordRepository.save(personRecord);
}

and call the methods as

performActionOnRecords(personId, associationDTO, (personRecord, document) -> personRecord.getDocuments().add(document)); // To add document

and,

performActionOnRecords(personId, associationDTO, (personRecord, document) -> personRecord.getDocuments().remove(document)); // To remove document
answered Mar 7, 2019 at 22:29
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.