r/SpringBoot • u/BluePillOverRedPill • 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
2
u/[deleted] Aug 23 '24
For an example of when you do need an interface -
I am building a trading platform and I need different types of data while executing, one that uses local data I have on my machine and one for apis.
I can create an interface for “data” and have a local implementation and an external implementation.
Then in my apis/frontend I can easily switch depending on what I need - I also have an interface for different providers so the actual specifics of each api are irrelevant.
This means I can write the code that processes data once, and I don’t need to refactor my entire project every time I want to add a new source of data.
If you don’t have a scenario like this an interface isn’t useful at all.
If you maintain levels of abstraction it should be quite easy to switch from a concrete implementation to an interface, if you realise the need is there