Most upvoted comment
Most popular programming book on Reddit. rank no. 44
Designing via Interface java?(r/java)
I don’t really like the term “design your system using interfaces” because it doesn’t tell you why. It’s a generic idea without any context.
It is better to start with a principle, like Dependency Inversion. Dependency Inversion says you should separate your code from its external dependencies. This is good, because it keeps your code isolated and not dependent on the particular details of things like storage.
Does your application use MySql? Does it use MongoDB? It doesn’t matter. In your interface, you can specify query methods for objects from a data store, and a method to save objects to your data store. Then implement the interface specifically for the data store. Your interface could be called
FooRepository and the implementation
MongoFooRepository. I dislike interfaces called
FooRepositoryImpl. This strongly suggests an interface isn’t necessary.
Interfaces are contracts that help you preserve your design and to explain what you need out of external dependencies.
Interfaces are good, but so are classes. Don’t overuse interfaces, because indirection isn’t always necessary or good. It can make your code impossible to follow and understand.
Start by learning principles like SOLID, which will help you understand where usage of interfaces makes sense. Agile Patterns, Principles and Practices is the best book I’ve read about this. Another book which does a great job of explaining how to properly use interfaces is Growing Object Oriented Software Guided By Tests.