Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you create an interface when there (currently) is only going to be one class that implements it?

Should you always create an interface if there's a possibility that there might be something else that could use it, or wait until there's an actual need for it then refactor to use an interface?

Programming to an interface generally seems like sound advice, but then there's YAGNI...

I guess maybe it depends on the situation. Right now I have an object representing a folder that can contain recipes or other folders. Instead of using Folder directly, should I worry about implementing something like IContainer? In case in the future I want to have a recipe that refers to other sub recipes (say an apple pie recipe that is also a container for a pie crust recipe)

like image 999
Davy8 Avatar asked Apr 06 '09 02:04

Davy8


2 Answers

It always depends on the situation. If you KNOW there is going to be another class using the interface, then yes, create the interface class to save time later. However, if you are not sure (and most of the time you aren't) then wait till you need it.

Now that doesn't mean to ignore the possibility of the interface - think about the object's public methods and such with an eye toward making an interface later, but don't clutter your codebase with anything that you don't actually NEED.

like image 54
Michael Kohne Avatar answered Oct 15 '22 07:10

Michael Kohne


There will be always a test that use it, right (you do unit tests, don't you?). Which means it's always N + 1 classes that use it, where N is number of classes that use your class in application.

Another purpose of interface besides dependency injection is separation of concern so that your class may actually implement multiple interfaces.

Keep all of that in mind but you can always have interface(s) introduced later via refactoring if not implemented in the beginning.

like image 3
topchef Avatar answered Oct 15 '22 06:10

topchef