When should you use interfaces? What are they good for?
Here are two examples.
1. Interfaces are an excellent way to implement reusability.
You can create a general interface for a number of situations
(such as a save to/load from disk interface.) You can then
implement the interface in a variety of different ways (e.g. for
formats such as tab delimited ASCII, XML and a database.)
You can write code that asks the object to "save itself to
disk" without having to worry what that means for the object
in question. One object might save itself to the database,
another to an XML and you can change this behavior over
time without having to rewrite the calling code.
This allows you to write reusable calling code that can work
for any number of different objects -- you don't need to know
what kind of object it is, as long as it obeys the common
interface.
2. Interfaces can also promote gradual evolution. On a
recent project I had some very complicated work to do and I
didn't know how to implement it. I could think of a "basic"
implementation but I knew I would have to change it later.
So I created interfaces in each of these cases, and created
at least one "basic" implementation of the interface that
was "good enough for now" even though I knew it would have
to change later.
When I came back to make the changes, I was able to create
some new implementations of these interfaces that added the
extra features I needed. Some of my classes still used
the "basic" implementations, but others needed the
specialized ones. I was able to add the new features to the
objects themselves without rewriting the calling code in most
cases. It was easy to evolve my code in this way because
the changes were mostly isolated -- they didn't spread all
over the place like you might expect.