Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need an interface that has only one implementation?

Tags:

java

oop

I have an interface, that has only one implementation. Following pair represents a simple java object. I want to remove that interface and use an object directly. But i want to understand when it's needed and why it was designed in that way. It was done definitely not to ease unit test coverage. So, why there is an interface with only one implementation in my project? Thanks.

like image 596
johnny-b-goode Avatar asked Dec 12 '22 15:12

johnny-b-goode


1 Answers

An interface is useful when you might extend/change your project. For instance, if you start a project by storing your data in a text file, and then decide to change to doing so from a database. If both of these are implementations of the same interface, then swapping the first out for the second is very simple. Just a case of swapping the concrete implementation in the class that uses it. For instance, simply changing

IStorage storage = new FileStorage();

to

IStorage storage = new DBStorage();

Whilst it may seem pointless to have an interface for a single implementation, it may save you a lot of refactoring effort later.

like image 197
Ben Green Avatar answered Dec 14 '22 06:12

Ben Green