B
Bruce Wood
jm said:Do interfaces get used in ASP.NET or is that more of an executable world?
Well, I don't write for ASP.NET, but yes, they would be used there,
too.
Rather than talking about ducks, I'd rather point out a classic use of
interfaces: your business layer needs to talk to a data layer in order
to persist / fetch business information. Typically what one does here
is write a bunch of Data classes that mediate between the business
layer objects and their representation in a SQL database. No problem so
far.
Now say that I want to demo my product on the road, and I don't
necessarily have access to a SQL database. I could, of course, use a
lightweight SQL database product on my laptop, but another option is to
write a whole other data layer that doesn't use a relational database
on the back end. Perhaps I want to store some demo data in XML files
and read from them instead. How would I do that?
Well, my SQL database persistence classes have their own inheritance
hierarchy: CustomerSqlData, say, inherits from SqlDataHandler, which
has lots of functionality common to classes that need to talk to SQL
databases. If I inherit CustomerXmlData from SqlDataHandler, or from
CustomerSqlData, then I get a bunch of code that has to do with SQL
databases that I don't want. If I create a whole second inheritance
hierarchy--CustomerXmlData inherits from XmlDataHandler--then how do I
tell my business layer that CustomerSqlData and CustomerXmlData are
really the same thing, just implemented in two different ways?
Interfaces are the answer. I create an interface called ICustomerData,
and simply tell my business layer class that it is talking to an
ICustomerData object. It doesn't need to know which one. The objects
don't need to be related by inheritance. In effect, my business layer
object is specifying a _contract_: "I will deal with any object that
implements the following functionality..." rather than specifying a
particular _class_ with which it will work. This frees you to implement
the required functionality in any class, anywhere in the inheritance
hierarchy, and effectively you can "plug and play" your data layer into
your business layer. You can even plug in some data classes that read
from XML and some that read from SQL if that turns out to be useful.
Interfaces, then, give you the capability to "chunk off" parts of your
application and build plug-and-play parts to implement the various
chunks. Each layer of your application knows only that the object it's
talking to implement the required contract (interfaces).
This sort of layering and plug-and-play capability applies equally well
to ASP.NET and WinForms.