Creating Service layer and DAO layer (interface+implementation) or implementation only

I suggest to create interfaces for service and for DAO. Very often you would like to mock service in unit tests of code, that use this serice. Also Spring, for example, forces you to use interfaces when you are using some Spring proxies for example for transactions. So you should have an interface for service.

DAO is more internal part, but I always try to use interfaces for them to simplify testing.


I prefer interface + implementations for the following reasons:

  • Interfaces becomes contracts: they tell you what is available to call, and you never worry about the implementation thereof, provided that the result is expected.
  • You can create customizable implementation of the interface without breaking other implementations of the same interface (generally useful when writing unit test). Customizing an implemented only class can bring more error than you don't notice easily.
  • It creates a framework that can be documented.

Implemented subclasses are used to create the business/application logic that conforms to the interface contract.