Ok the great thing about programming to an interface is that it allows you to interchange specific classes as long as the new classes implement everything in that interface.
e.g. i program my dataSource object to an interface so i can change it between an xml reader and a sql database reader.
does this mean ideally every class should be programmed to an interface?
when is it not a good idea to use an interface?
When the YAGNI principle applies.
Interfaces are great but it's up to you to decide when the extra time it takes developing one is going to pay off. I've used interfaces plenty of times but there are far more situations where they are completely unnecessary.
Not every class needs to be flexibly interchanged with some other class. Your system design should identify the points where modules might be interchangeable, and use interfaces accordingly. It would be silly to pair every class with an additional interface file if there's no chance of that class ever being part of some functional group.
Every interface you add to your project adds complexity to the codebase. When you deal with interfaces, discoverability of how the program works is harder, because it's not always clear which IComponent is filling in for the job when consumer code is dealing with the interface explicitly.
IMHO, you should try to use interfaces a lot. It's easier to be wrong by not using an interface than by using it.
My main argument on this is because interfaces help you make a more testable code. If a class constructor or a method has a concrete class as a parameter, it is harder (specially in c#, where no free mocking frameworks allow mocking non-virtual methods of concrete classes) for you to make your tests that are REAL unit tests.
I believe that if you have a DTO-like object, than it's overkill to use an interface, once mocking it may be maybe even harder than creating one.
If you're not testing, using dependency injection, inversion of control; and expect never to do any of these (please, avoid being there hehe), then I'd suggest interfaces to be used whenever you will really need to have different implementations, or you want to limit the visibility one class has over another.
Use an interface when you expect to need different behaviours used in the same context. I.e. if your system needs one customer class which is well defined, you probably don't need to use an ICustomer interface. But if you expect a class to comply to a certain behaviour s.a. "object can be saved" which applies to different knids of objects then you shoudl have the class implement an ISavable interface.
Another good reason to use an interface is if you expect different implementations of one kind of object. For example if ypu plan an SMS-Gateway which will route SMS's through several different third-party services, your classes should probably implent a common interface s.a. ISmsGatewayAdapter so your core system is independent from the specific implementation you use.
This also leads to 'dependecy injection' which is a technique to further decouple your classes and which is best implemented by using interfaces
The real question is: what does your class DO? If you're writing a class that actually implements an interface somewhere in the .NET framework, declare it as such! Almost all simple library classes will fit that description.
If, instead, you're writing an esoteric class used only in your application and that cannot possibly take any other form, then it makes no sense to talk about what interfaces it implements.
Starting from the premise of, "should I be implementing an interface?" is flawed. You neither should be nor shouldn't be. You should simply be writing the classes you need, and declaring what they do as you go, including what interfaces they implement.
I prefer to code as much as possible against an interface. I like it because I can use a tool like StructureMap to say "hey...get me an instance of IWidget" and it does the work for me. But by using a tool like this I can programatically or by configuration specify which instance is retrieved. This means that when I am testing I can load up a mock object that conforms to an interface, in my development environment I can load up a special local cache, when I am in production I can load up a caching farm layer, etc. Programming against an interface provides me a lot more power than not programming against an interface. Better to have and not need than need and not have applies here very well. And if you are into SOLID programming the easiest way to achieve many of those principles sort of begins by programming against an interface.
As a general rule of thumb, I think you're better off overusing interfaces a bit than underusing them a bit. Err on the side of interface use.
Otherwise, YAGNI applies.
If you are using Visual Studio, it takes about two seconds to take your class and extract an interface (via the context menu). You can then code to that interface, and hardly any time was spent.
If you are just doing a simple project, then it may be overkill. But on medium+ size projects, I try to code to interfaces throughout the project, as it will make future development easier.
Related
I am increasingly seeing examples of this style. This happens irrespective of whether the interface is ever likely to be needed. In other case, the adoption of new interfaces prove helpful. However, it cannot always be predicted whether it will be used or not but a new interfaces are created for new properties to conform to... Best practice or not?
As usual, it depends. If you're writing a public API, this approach is extremely powerful. An example of this is the Progistics / Connectship API. At the time that I used it, there was a single concrete class. The rest of the public interface was all interfaces. They were able to rip out the entire implementation of the product and rewrite it, leaving the interfaces untouched.
Of course, there is a cost associated with this. You have to put a lot of up front time and effort into making an elegant API if you're going to want to cast it in stone (of course, this is the case whether you choose to use interfaces or not).
On the other hand, if you're writing the data access layer for an internal business application, you might not reap as many rewards.
In theory, you should have an interface or abstract class for any class that contains business logic - so you can unit test it and/or easily swap implementations. Classes that are used to represent data - model classes - don't have to implement an interface to be a "best practice" (it has to end somewhere).
I'd have to go with the Extreme Programming and YAGNI (You ain't gonna need it) practice. Only extract the interface when you need it for another class. Otherwise, it's just adding overhead.
The exception, of course, is when you need to add a Mock object into your testing scheme, and subclassing doesn't achieve what you want.
This topic is related to Emergent Design. I consider it to be the mark of excellent designers.
I'd say NOT. If familiar objects share a property, then create the interface. If the need arises then create the interfaces. I think that creating interfaces by default for all properties creates too much overhead.
Should a class implement an interface always in order to enforce a sort of 'contract' on the class?
When shouldn't a class implement an interface?
Edit: Meaning, when is it worthwhile to have a class implement an interface? Why not have a class just have public members and private members with various accessor/setter functions?
(Note: Not talking about COM)
No, an interface is not always required - the public members of the class already form a contract.
An interface is useful when you want to be able to exchange one class for another when both offer similar functionality. Using an interface allows you to decouple the contract from the specific implementation. However this decoupling is not always necessary or useful.
Many classes in the .NET framework do not implement any interfaces.
Only use an interface when it is needed.
That is: when you want to have different implementations for a certain abstraction.
When, in the future, it seems that it would be better to have an interface for a specific class (because for instance, you want to have another implementation for the same concept), then you can always create the interface from your existing class. (ExtractInterface refactoring)
Interfaces become more necessary when you are doing unit testing, but it all depends on the context of your development. As Mark said, an interface IS the contract and implementing it forces you to adhere to the "rules" of that contract.
If you are trying to enforce the implementation of certain methods, then using an interface is perfect for that.
There are some nice examples here:
http://msdn.microsoft.com/en-us/library/ms173156.aspx
http://msdn.microsoft.com/en-us/library/87d83y5b(VS.80).aspx
An interface, here meaning the code construct and not the design abstraction, supports a basic principle of code design called "loose coupling". There are some more derived principles that tell you HOW code should be loosely coupled, but in the main, loose coupling helps allow changes to code to affect as small an area of the codebase as possible.
Consider, for example, a calculation of some arbitrary complexity. This calculation is used by 6 different classes, and so to avoid duplicating code, the calculation is encapsulated in its own class, Calculator. The 6 classes each contain a reference to a Calculator. Now, say that your customer comes to you and says that in one usage of Calculator, if certain conditions are met, a different calculation should be used instead. You might be tempted to simply put these two rules (usage rule and business rule) and the new calculation algorithm into the Calculator class, but if you do so, then two things will happen; first, you make Calculator aware of some implementation details (how it's used) outside of its scope, that it doesn't need to know and that can change again later. Second, the other 5 classes that use Calculator, which were working just fine as-is, will have to be recompiled since they reference the changed class, and will have to be tested to ensure you didn't break their functionality by changing the one for the 6th class.
The "proper" solution to this is an interface. By defining an interface ICalculator, that exposes the method(s) called by the other classes, you break the concrete dependence of the 6 classes on the specific class Calculator. Now, each of the 6 classes can have a reference to an ICalculator. On 5 of these classes, you provide the same Calculator class they've always had and work just fine with. On the 6th, you provide a special calculator that knows the additional rules. If you had done this from the beginning, you wouldn't have had to touch the other 5 classes to make the change to the 6th.
The basic point is, classes should not have to know the exact nature of other objects they depend on; they should instead only have to know what that object will do for them. By abstracting what the object DOES from what the object IS, multiple objects can do similar things, and the classes that require those things don't have to know the difference.
Loose coupling, along with "high cohesion" (objects should usually be specialists that know how to do a small, very highly-related set of tasks), is the foundation for most of the software design patterns you'll see as you progress into software development theory.
In contrast to a couple of answers, there are design methodologies (e.g. SOLID) that state that you should ALWAYS set up dependencies as abstractions, like an abstract base class or an interface, and NEVER have one class depend upon another concrete class. The logic here is that in commercial software development, the initial set of requirements for an application is very small, but it is a safe assumption, if not a guarantee, that the set of requirements will grow and change. When that happens, the software must grow. Creating even smaller applications according to strict design principles allows extending the software without causing the problems that are a natural consequence of bad design (large classes with lots of code, changes to one class affecting others in unpredictable ways, etc). However, the art of software development, and the time and money constraints of same, are such that you can (and have to) be smart and say "from what I know of the way this system will grow, this is an area that needs to be well-designed to allow adaptation, while this other section will almost surely never change". If those assumptions change, you can go back and refactor areas of code you designed very simply to be more robust before you extend that area. But, you have to be willing and able to go back and change the code after it's first implemented.
This once again comes down to what he means by "interface". There is some ambiguity between the term interface and Interface. When the term Interface is used it means an object that has no method declarations. When the term interface is used it means that you utilize a pre-defined set of functions (whether they be implemented or not) and override them with your logic if necessary. An example would be:
abstract class Animal
class Dog extends Animal
In this instance Animal == interface (or contract) for Dog
interface Measurable
class Cup implements Measurable
In this instance Measurable == Interface for Cup
A class should not implement interface/s unless you want to tell other parts of your program - "This class can do these things (but not specify how exactly it does what it does)".
When would you want to do that?
For example, say you have a game in which you have animals.. And say whenever an animal sees a human it makes it's sound (be it a bark, a roar etc.).
If all animals will implement interface IMakeSound in which there is a method called MakeSound, you will not have to care about what kind of animal it is that should make that sound.. All you'll have to do is to use the "IMakeSound" part of the animal, and call it's method.
I should add that when one reads in a class declaration that it implements a certain interface, it tells him a lot about that class, which is another benefit.
You may not always want an interface. Consider you can accomplish similar tasks with a delegate. In Java I used the Runnable Interface for multithreaded applications. Now that I program in .NET I rely a lot on delegates to accomplish my mulithreaded applications. This article helps explains the need for an Delegate vs an Interface.
When to Use Delegates Instead of Interfaces (C# Programming Guide)
Delegates provide a little more flexibility as in Java I found that any task that I accomplished in C with a function pointer now required incasulation with an an Interface.
Although, there are lots of circumstances for an Interface. Consider IEnumerable, it is designed to allow you to iterate over various collection without needing to understand how the underlying code works. Interfaces are great for when you need need to exchange one class for another but require a similar Interface. ICollection and IList provide a set of similar functionality to accomplish an operation on a collection without worrying about the specifics.
If you would like to better understand Interfaces I suggest you read "Head First Design Patterns".
In the project I'm working on, I've noticed that for every entity class there is an interface. It seems that the original motivation was to only expose interfaces to other project/solutions.
I find this completely useless, and I don't see the point in creating an interface for every class. By the way, those classes don't have any methods just properties and they don't implement the same interface.
Am I wrong? Or is it a good practice?
Thx
I tend to create an interface for almost every class mainly because of unit testing - if you use dependency injection and want to unit test a class that depends on the class in question, than the standard way is to mock an instance of the class in question (using one of the mocking frameworks, e.g. Rhino-Mocks). However, practically it is only possible only for interfaces, not concrete implementations (yes, theoretically you can mock a concrete class, but there are many painful limitations).
There may be more to the setup than described here that justifies the overhead of interfaces. Generally they're very useful for dependency injection and overall separation of concerns, unit testing and mocking, etc.. It's entirely possible that they're not being used for this purpose (or any other constructive purpose, really) in your environment, though.
Is this generated code, or were these manually created? If the former, I suspect the tool generating them is doing so to prepare for such a use if the developer were so inclined. If the latter, maybe the original designer had something in mind?
For my own "best practices" I almost always do interface-driven development. It's generally a good practice to separate out concerns from one another and use the interfaces as contracts between them.
Exposing interfaces publicly has value in creating a loosely-coupled, behaviour-driven architecture.
Creating an interface for every class - especially if the interface just exposes every public method the class has in a single interface - is a bad implementation of the concept, and (in my experience) leads to more complex code and no improvement in architecture.
It's useful for tests.
A method may take a parameter of type ISomething, and it can be either SqlSomething or XmlSomething, where ISomething is the interface, and SqlSomething and XmlSomething are classes that implement the interface, depending whether you're doing tests (you pass XmlSomething in this case) or running the application (SqlSomething).
Also, when building a universal project, that can work on any database, but aren't using an ORM tool like LINQ (maybe because the database engine might not support LINQ to SQL), you define interfaces, with methods that you use in the application. Later on, developers will implement the interfaces to work with the database, create MySQLProductRepository class, PostgreSQLProductRepository class, that both inherit the same interface, but have different functionality.
In the application code any method takes a parameter a repository object of type IProductRepository, which can be anything.
IMHO it sounds that writing interfaces for no reason is pointless. You cant be totally closed minded but in general doing things that are not immediatly useful tend to accumulate as waste.
The agile concept of Its either adding value or taking value comes to mind.
What happens when you remove them? If nothing then ... what are they there for?
As a side note. Interfaces are extremely useful for Rhino Mocks, dependency injection and so on ...
If those classes only have properties, then interfaces don't add much value, because there's no behavior that is being abstracted.
Interfaces can be useful for abstraction, so the implementation can be mocked in unit tests. But in a well-designed application the business/domain entities should have very little reasons to be mocked. Business/domain services on the other hand are a excellent candidate for interface abstraction.
I have created interfaces for my entities once, and it didn't add any value at all. It only made me realize my design was wrong.
It seems to be an interface is superior to an abstract base class primarily if/when it is necessary to have a class which implements the interface but inherits from some other base class. Multiple inheritance is not allowed, but multiple interface implementations are.
The main caveat I see with using interfaces rather than abstract classes (beyond the extra source code required) is that changing anything in an interface necessitates recompilation of any and all code which uses that interface. By contrast, adding public members to a base class generally only requires recompilation of the base class itself.(*)
(*) Due to the way extension methods are handled, adding members to a class won't "require" recompiling code which uses that class, but may cause code which uses extension methods on the class to change meaning the next time it (the extension-method-using code) is recompiled.
There is no way to tell the future and see if you're going to need to program against an interface down-the-road. But if you decide later to make everything use an interface and, say, a factory to create instances of unknown types (any type that implements the interface), then it is quicker to restrict everyone to programming against an interface and a factory up-front than to replace references to MyImpl with references to IMyInterface later, etc.
So when writing new software, it is a judgment call whether to program against an interface or an implementation, unless you are familiar with what is likely to happen to that kind of software based on previous experiences.
I usually keep it "in flux" for a time whether or not I have an interface, a base class, or both, and even whether the base class is abstract (it usually is). I will work on a project (usually a Visual Studio solution with about 3 to 10 projects in it) for a while (a couple of days, maybe) before I refactor and / or ask for a second opinion. Once a final decision is reached and the code is refactored and tested, I tell fellow devs that it is ready for use.
For unit testing, it's either interfaces everywhere or virtual methods everywhere.
Sometimes I miss Java :)
I have seen code where every class has an interface that it implements.
Sometimes there is no common interface for them all.
They are just there and they are used instead of concrete objects.
They do not offer a generic interface for two classes and are specific to the domain of the problem that the class solves.
Is there any reason to do that?
No.
Interfaces are good for classes with complex behaviour, and are especially handy if you want to be able to create a mock or fake implementation class of that interface for use in unit tests.
But, some classes don't have a lot of behaviour and can be treated more like values and usually consist of a set of data fields. There's little point in creating interfaces for classes like this because doing so would introduce unnecessary overhead when there's little point in mocking or providing alternative implementations of the interface. For example, consider a class:
class Coordinate
{
public Coordinate( int x, int y);
public int X { get; }
public int y { get; }
}
You're unlikely to want an interface ICoordinate to go with this class, because there's little point in implementing it in any other way than simply getting and setting X and Y values.
However, the class
class RoutePlanner
{
// Return a new list of coordinates ordered to be the shortest route that
// can be taken through all of the passed in coordinates.
public List<Coordinate> GetShortestRoute( List<Coordinate> waypoints );
}
you probably would want an IRoutePlanner interface for RoutePlanner because there are many different algorithms that could be used for planning a route.
Also, if you had a third class:
class RobotTank
{
public RobotTank( IRoutePlanner );
public void DriveRoute( List<Coordinate> points );
}
By giving RoutePlanner an interface, you could write a test method for RobotTank that creates one with a mock RoutePlanner that just returns a list of coordinates in no particular order. This would allow the test method to check that the tank navigates correctly between the coordinates without also testing the route planner. This means you can write a test that just tests one unit (the tank), without also testing the route planner.
You'll see though, it's quite easy to feed real Coordinates in to a test like this without needing to hide them behind an ICoordinate interface.
After revisiting this answer, I've decided to amend it slightly.
No, it's not best practice to extract interfaces for every class. This can actually be counterproductive. However, interfaces are useful for a few reasons:
Test support (mocks, stubs).
Implementation abstraction (furthering onto IoC/DI).
Ancillary things like co- and contra-variance support in C#.
For achieving these goals, interfaces are considered good practice (and are actually required for the last point). Depending on the project size, you will find that you may never need talk to an interface or that you are constantly extracting interfaces for one of the above reasons.
We maintain a large application, some parts of it are great and some are suffering from lack of attention. We frequently find ourselves refactoring to pull an interface out of a type to make it testable or so we can change implementations whilst lessening the impact of that change. We also do this to reduce the "coupling" effect that concrete types can accidentally impose if you are not strict on your public API (interfaces can only represent a public API so for us inherently become quite strict).
That said, it is possible to abstract behaviour without interfaces and possible to test types without needing interfaces, so they are not a requirement to the above. It is just that most frameworks / libraries that you may use to support you in those tasks will operate effectively against interfaces.
I'll leave my old answer for context.
Interfaces define a public contract. People implementing interfaces have to implement this contract. Consumers only see the public contract. This means the implementation details have been abstracted away from the consumer.
An immediate use for this these days is Unit Testing. Interfaces are easy to mock, stub, fake, you name it.
Another immediate use is Dependency Injection. A registered concrete type for a given interface is provided to a type consuming an interface. The type doesn't care specifically about the implementation, so it can abstractly ask for the interface. This allows you to change implementations without impacting lots of code (the impact area is very small so long as the contract stays the same).
For very small projects I tend not to bother, for medium projects I tend to bother on important core items, and for large projects there tends to be an interface for almost every class. This is almost always to support testing, but in some cases of injected behaviour, or abstraction of behaviour to reduce code duplication.
Let me quote OO guru, Martin Fowler, to add some solid justification to the most common answer in this thread.
This excerpt comes from the "Patterns of Enterprise Application Architecture" (enlisted in the "classics of programming" and\or the "every dev must read" book category).
[Pattern] Separated Interface
(...)
When to Use It
You use Separated Interface when you need to break a dependency between two parts of the system.
(...)
I come across many developers who have separate interfaces for every class they write. I think this is excessive, especially for
application development. Keeping separate interfaces and
implementations is extra work, especially since you often need factory
classes (with interfaces and implementations) as well. For
applications I recommend using a separate interface only if you want
to break a dependency or you want to have multiple independent
implementations. If you put the interface and implementation
together and need to separate them later, this is a simple refactoring
that can be delayed until you need to do it.
Answering your question: no
I've seen some of the "fancy" code of this type myself, where developer thinks he's SOLID, but instead is unintelligible, difficult to extend and too complex.
There's no practical reason behind extracting Interfaces for each class in your project. That'd be an over-kill. The reason why they must be extracting interfaces would be the fact that they seem to implement an OOAD principle "Program to Interface, not to Implementation". You can find more information about this principle with an example here.
Having the interface and coding to the interface makes it a ton easier to swap out implementations. This also applies with unit testing. If you are testing some code that uses the interface, you can (in theory) use a mock object instead of a concrete object. This allows your test to be more focused and finer grained.
It is more common from what I have seen to switch out implementations for testing (mocks) then in actual production code. And yes it is wroth it for unit testing.
I like interfaces on things that could be implemented two different ways, either in time or space, i.e. either it could be implemented differently in the future, or there are 2 different code clients in different parts of the code which may want a different implementation.
The original writer of your code might have just been robo coding, or they were being clever and preparing for version resilience, or preping for unit testing. More likely the former because version resilience an uncommon need-- (i.e. where the client is deployed and can't be changed and a component will be deployed that must be compatible with the existing client)
I like interfaces on things that are dependencies worth isolation from some other code I plan to test. If these interfaces weren't created to support unit tests either, then I'm not sure they're such a good idea. Interface have a cost to maintain and when it comes time to make an object swappable with another, you might want to have an interface apply to only a few methods (so more classes can implement the interface), it might be better to use an abstract class (so that default behaviors can be implemented in an inheritance tree).
So pre-need interfaces is probably not a good idea.
If is a part of the Dependency Inversion principle. Basically code depends on the interfaces and not on the implementations.
This allows you to easy swap the implementations in and out without affecting the calling classes. It allows for looser coupling which makes maintenance of the system much easier.
As your system grows and gets more complex, this principle keeps making more and more sense!
I don't think it's reasonable for Every class.
It's a matter of how much reuse you expect from what type of a component. Of course, you have to plan for more reuse (without the need to do major refactoring later) than you are really going to use at the moment, but extracting an abstract interface for every single class in a program would mean you have less classes than needed.
Interfaces define a behaviour. If you implement one or more interfaces then your object behaves like the one or other interfaces describes. This allows loose coupling between classes. It is really useful when you have to replace an implementation by another one. Communication between classes shall always be done using interfaces excepting if the classes are really tightly bound to each other.
There might be, if you want to be sure to be able to inject other implementations in the future. For some (maybe most) cases, this is overkill, but it is as with most habits - if you're used to it, you don't loos very much time doing it. And since you can never be sure what you'll want to replace in the future, extracting an interface on every class does have a point.
There is never only one solution to a problem. Thus, there could always be more than one implementation of the same interface.
It might seem silly, but the potential benefit of doing it this way is that if at some point you realize there's a better way to implement a certain functionality, you can just write a new class that implements the same interface, and change one line to make all of your code use that class: the line where the interface variable is assigned.
Doing it this way (writing a new class that implements the same interface) also means you can always switch back and forth between old and new implementations to compare them.
It may end up that you never take advantage of this convenience and your final product really does just use the original class that was written for each interface. If that's the case, great! But it really didn't take much time to write those interfaces, and had you needed them, they would've saved you a lot of time.
The interfaces are good to have since you can mock the classes when (unit-) testing.
I create interfaces for at least all classes that touches external resources (e.g. database, filesystem, webservice) and then write a mock or use a mocking framework to simulate the behavior.
Why do you need interfaces? Think practically and deeply. Interfaces are not really attached to classes, rather they are attached to services. The goal of interface is what you allow others to do with your code without serving them the code. So it relates to the service and its management.
See ya
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.
Think of an interface as a contract to define semantics, or a concept. That's a general approach and not really language specific. In context of OO, if you are working in a single inheritance model, there is an excellent case to be made for preferring interfaces over classes for defining your object model, since that single super class pathway is fairly precious and you want to save it for something more 'substantial' than defining properties that are exposed on an object, or methods.
To have IContainer semantics (contract) is a fairly poor reason to make an interface out of your folder; better to have your folder (if it is doing any non-trivial logic) 'implement' the (likely already existing) IContainer or ICollection interface in your language's core frameworks.
As always, the better choice is fairly dependent on the specific problem. In case of your recipes that are also folders (?!) you are probably thinking of a parent-child, or composition, relationship -- a semantic that can (and should) be expressed using interfaces if you will have other elements in your system 'operate' on things that are composed using that sort of semantics.
There is a bit of overhead (programming wise) with interfaces, and, if you find yourself when you are done with nothing more than a set of Woof and IWoof classes and interfaces, then you'll know you probably didn't need to express your problem in terms of interfaces -- simple classes would have been sufficient.
As a rule, for any I, you should have at least a couple of concrete classes (with more meaningful names other than IImpl, or ).
Hope that helps.
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.
Generally, you shouldn't bother with creating an interface if only one class is going to implement it, even if you anticipate a possible class for it since there may be implementation issues that won't come up until the class is actually tested in a scenario, in which case a prematurely created interface may have too many memebrs or may be missing a member.
For example, the .NET Framework Bas Class Library team has admitted to prematurely designing ICollection when it included a SyncRoot property. For the later generic ICollection<T> they decided to remove it (http://blogs.msdn.com/bclteam/archive/2005/03/15/396399.aspx).
If you are going to create a mock object implementing the same interface then that would count as a second implementation that justifies creating the inteface. Not all unit tests warrant a mock-style interface, though.
I would say it depends more on how many places you're going to use the class, and less on how many classes might possibly implement the interface. If you're only using Folder in one or two places then I would say wait until there's an actual need for the interface before you implement it and refactor. However, if Folder is going to be used in 100 different places, then you can save some time by programming to an interface up front.
A lot of the people have already outlined very sound advice.
One thing I'd like to add is that if you are looking to avoid direct hard dependencies on concrete classes then interfaces will help by providing loose coupling.
If you are creating a plug-in based architecture then interfaces are definitely the way to go. Also, if you are planning to write unit tests either side by side or later down the line, you will probably notice that code which calls into your folder class(es) will have to carry around a concrete implementation for the calling code to be testable.
If your concrete implementation of the folder class(es) is in turn talking to a DB or a service then you will need to have that carried over into your tests as well which will get unwieldy very quickly.
Just my 2 cents.