4

In Spring, while creating a DAO class to access to database, i also implement a DAO interface. i.e. :

public interface EmployeeDAO {
    public void addEmployee(Employee emp);
}

@Repository
public class EmployeeDAOImpl implements EmployeeDAO {
    public void addEmployee(Employee emp) {
        /* code here */
    }
}

Why do we implement an interface? Why "public class EmployeeDAOImpl" is not enough? Thank you.

user1811660
  • 125
  • 1
  • 8

2 Answers2

5

"Program to an interface, not an implementation." is a basic OO design principle. Following this principle make your code more extensible. Let's take some examples:

  1. If you're writing some testcases for uplevel services that will invoke EmployeeDAO, you can simple write a MockEmployeeDAO class that implements EmployeeDAO interface, then you are able to simulate many scenarios for the test without actually querying the DB.
  2. If may need to change the implementation of your data layer, for example, migrate from relational DB to NoSql DB, or adding a cache layer. Programming to the DAO interface makes it possible to make that changes without modifying uplevel codes.

If you don't see any benefit currently, just follow the principle. I'm sure that you'll get benefits in the future.

Weibo Li
  • 3,565
  • 3
  • 24
  • 36
1

this question is almost similar to this link

Using interfaces for writing DAO classes

I hope this will clear your doubt

Community
  • 1
  • 1
Gurinder
  • 943
  • 2
  • 9
  • 19