r/SpringBoot • • Aug 23 '24

Interface for each service?

Hi Everyone!

I’m a bit confused about the use of interfaces for all services in Spring Boot. I understand that interfaces serve as a contract and offer benefits like easier testing and flexibility for future changes. However, I’ve also read that if you’re not planning to have multiple implementations of a service, using interfaces might be unnecessary. Could you clarify the best practices for using interfaces in this context, and explain how they impact dependency injection and testing?

24 Upvotes

23 comments sorted by

View all comments

2

u/asarathy Aug 23 '24

People hating on 'useless' interfaces are really protesting too much. There is value in being explicit about what parts of your class are designated for out side use. Other people having access to the concrete implementation often leads to short cuts such as just making a helper method public instead of refactoring it out for reuse.

While it's equally trivial to refactor out an interface later when you need it, it's not really a big deal to have it from the start, and enforcing better practices and the muscle memory of that is probably better for most corporate settings.

1

u/Big_Sell5559 Aug 24 '24

All depends of the use case and the purpose of your project. If you pretend to build a library for external use, of course you'll have to implement with interfaces all around for providing your users with the needed flexibility. If the Op is asking for the legacy practice of creating interfaces for controllers, services and components in Spring, you'll have to bear in mind that in 2024 with modern Java and Spring is totally superfluous and a bad practice.

1

u/asarathy Aug 24 '24

Right. If you keep a small spring domain rest service sure. If yo are dealing with a monolith though enforcing this stuff is important because it makes life easier in the future if you want to split things up later. T hat's why i think getting the muscle memory is important

1

u/Big_Sell5559 Aug 24 '24

My vision is that you have to enforce the boundaries from the beginning and try to avoid complete monoliths. Nowadays you have very powerful options to architect you project, no matter the size, as Spring Modulith, that provides you with tools for building a correct architectural software project. Ancient methods filling the codebase with interfaces are harmful. For more detail, try with https://spring.io/projects/spring-modulith

1

u/asarathy Aug 24 '24

I agree but sometimes you don't make all the calls.