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

3

u/dns1211 Aug 24 '24 edited Aug 24 '24

Using an interface for each services is considered a good practice. it helps with testing, maintainance, extensibility.

For example when using dependency injection and testing. If your controller depends on an interface, you could easily implement a FailService to testing purpose.

Keep in mind that your code base likely grow over the time, so if it’s a project at work, always follow the standards for the sake of your colleagues.

2

u/Big_Sell5559 Aug 24 '24

That was necessary in earlier versions of Spring Framework. Nowadays you can test everything without cluttering your code with useless interfaces

1

u/dns1211 Aug 25 '24

It is a clear example for him to grasp. However in some complex cases a mock might struggle to handle your bussiness logic which is when the fake class becomes useful.

Keep in mind SOLID principles. Tbh it’s your code, your choice. enjoy your coding !