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?

\$\endgroup\$
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
\$\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.