需要Dao和服务接口(Need Of Dao And Service Interfaces)

其他开发 IT屋
百度翻译此文   有道翻译此文
问 题

I am new to spring Mvc and in a lot of tutorials i found there is a Dao interface like this

public interface StudentDAO {

public List<Student> getStudents();
public void addEntry(Student student);
public void updateEntry(Student student);
public void deleteEntry(Student student);
public Student getStudentById(int id);

}

and Also services like this

public interface StudentService {

public List<Student> getStudents();
public void addEntry(Student student);
public void updateEntry(Student student);
public void deleteEntry(Student student);
public Student getStudentById(int id);

}

and there are implementations for these interfaces. My Question is Why we need interfaces rather than direct implementation classes?.

解决方案

Perhaps the simplest concrete illustration for the need is testing.

With the DAO interface, you can test your application's logic without the need to have a DB running that's accessible from the machine running tests, simply by swapping your DAO implementation for a dummy one during tests. That dummy implementation can then provide consistent data for tests that doesn't change between test runs, cannot be overwritten in DB by accident, is versioned in you Git/SVN/whatever etc.


In general, this is part of the Program to an interface, not an implementation design principle.

In my experience, this separation of interface vs. implementation is a good idea even if you're never going to have multiple implementations, because it encourages programmers to think more deeply about the contract of the class.

Note that the principle is not universally accepted, here are some counter-arguments for example.

本文地址:IT屋 » Need Of Dao And Service Interfaces

问 题

我是初学Mvc的新手,在很多教程中我发现有这样的Dao界面



 公共界面StudentDAO {

public List< Student> getStudents();
public void addEntry(学生);
public void updateEntry(学生);
public void deleteEntry(学生);
public Student getStudentById(int id);


}



以及此类服务



  public interface StudentService {

public List< Student> getStudents();
public void addEntry(学生);
public void updateEntry(学生);
public void deleteEntry(学生);
public Student getStudentById(int id);


}



并且有实现这些接口。我的问题是为什么我们需要接口而不是直接实现类?


解决方案

也许最简单的具体例子就是测试。



使用DAO接口,您可以测试应用程序的逻辑,而无需运行可从运行测试的计算机访问的数据库,只需在测试期间将DAO实现交换为虚拟实现。然后,该虚拟实现可以为测试运行之间不会改变的测试提供一致的数据,不能在DB中意外覆盖,在Git / SVN /等等中进行版本化。






一般情况下,这是编程到界面,而不是实现设计原则。



根据我的经验,即使你',这种界面与实现的分离也是一个好主意。永远不会有多个实现,因为它鼓励程序员更深入地思考类的契约



注意原则是不是普遍接受的,这里有一些反驳例如。


本文地址:IT屋 » 需要Dao和服务接口

官方微信
扫一扫关注IT屋
微信公众号搜索 “ IT屋 ” ,选择关注
与百万开发者在一起
}