Should you create an interface when there is (currently) a single class that implements it?

advertisements

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)


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.