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.

3

u/Rough_Acanthaceae_29 Aug 23 '24

There is value in being explicit about what parts of your class are designated for out side use.

Yeah, but you can use access modifiers for that.

0

u/asarathy Aug 24 '24

It doesn't solve the issue of quick/sloppy fixes where instead of refactoring a method out to a better place people just change it to public

2

u/Rough_Acanthaceae_29 Aug 24 '24

If someone is in hurry to get shit done - they love that it’s only one keyword and they’ll fix afterwards. If they’re doing it because they don't know better, interface won't stop them. Either way, interface achieves the same but with extra work…

0

u/asarathy Aug 24 '24

Nothing solves that issue. You have to have everyone enforcing things at PR. It's more difficult in larger projects with lots of people with merge access though so that's where being somewhat dogmatic about this stuff helps