DEV Community

Igor Rudel
Igor Rudel

Posted on

Dica Java: Functional Interface #001

É bem comum no desenvolvimento de aplicações Java termos injeções de dependências de uma mesma bean em diferentes locais e em muitas vezes em relações entre beans como nos exemplos abaixo:

@Service
@RequiredArgsConstructor
public class PersonUpdater {

    private final PersonValidator validator;
    private final DocumentService documentService; //outras utilizações no fluxo de atualização

    public Person toUpdate(final Person person) {
        validator.validate(person);

        //...fluxo de atualização de pessoa

        return person;
    }
}
Enter fullscreen mode Exit fullscreen mode
@Component
@RequiredArgsConstructor
public class PersonValidator {

    private final DocumentService documentService;

    public void validate(final Person person) {
        if (person.isAdult() && person.isMale()) {
            final var documents = documentService.getMilitaryDocuments(person.getId());

            //validações necessárias
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

A bean DocumentService foi injetada tanto em PersonUpdater como em PersonValidator. Na PersonUpdater a bean pode ser utilizado para outros fluxos da atualização, porém, na PersonValidator a bean será APENAS utilizada para a busca de documentos militares QUANDO for a atualização de uma pessoa do gênero masculino e maior de idade. Uma possibilidade de ter o mesmo resultado são os exemplos abaixo:

@Service
@RequiredArgsConstructor
public class PersonUpdater {

    private final PersonValidator validator;
    private final DocumentService documentService; //outras utilizações no fluxo de atualização

    public Person toUpdate(final Person person) {
        validator.validate(person, () -> documentService.getMilitaryDocuments(person.getId()));

        //...fluxo de atualização de pessoa

        return person;
    }
}
Enter fullscreen mode Exit fullscreen mode
@Component
@RequiredArgsConstructor
public class PersonValidator {

    public void validate(final Person person,
                         final Supplier<List<Document>> documentsSupplier) {
        if (person.isAdult() && person.isMale()) {
            final var documents = documentsSupplier.get();

            //validações necessárias
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Com as Interfaces Funcionais, abre-se um leque de opções de utilizações de comportamentos de uma aplicação Java! Elas flexibilizam a utilização via argumento de método (como no exemplo) e via atributo de alguma classe.

Além da injeção de dependência ser feito apenas em um local, temos:

  • diminuir o acoplamento do validador
  • aumentar a flexibilidade do método

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay