views:

36

answers:

2

In the Spring web app I am working on, there is a service layer that relates to the rest of the web app structure like this:

com/
    myapp/
          controller/
          model/
          service/

This service layer is made up of interface and implementation classes.

Why is it so important to have interfaces for all of these classes?

Why not just Class files?

+1  A: 

The Interfaces allow you to pass different implementations of those interfaces without changing the underlying code.

For example, if a model only wanted HashMap and you had a TreeMap, you'd be in trouble. But if the model accepted Map (ok, pretend it's an Interface) then it would work with either HashMap or TreeMap.

Tony Ennis
Map *is* an interface
seanizer
+1  A: 

I believe Spring will create a proxy class in many instances. The proxy class implements your interface, and eventually delegates to your implementation, but may do some stuff in between like transaction management. If you use an interface then your code doesn't care whether it gets your implementation directly, or a spring proxy implementation.

digitaljoel