为什么应该优先选择Java类的接口? [英] Why should the interface for a Java class be prefered?

查看:220
本文介绍了为什么应该优先选择Java类的接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PMD 会报告违反:

  ArrayList< Object> list = new ArrayList< Object>(); 

违反是避免使用类似ArrayList的实现类型; p>

以下行将更正违例:

  List< Object& list = new ArrayList< Object>(); 

为什么要使用 List 而不是 ArrayList

解决方案

对于良好的封装和松散耦合你的代码。



在编写自己的API时,遵循这种做法是个好主意。如果你这样做,你会发现以后更容易添加单元测试到你的代码(使用Mocking技术),并改变底层实现如果需要在未来。



以下是好文章



希望它有帮助!


PMD would report a violation for:

ArrayList<Object> list = new ArrayList<Object>();

The violation was "Avoid using implementation types like 'ArrayList'; use the interface instead".

The following line would correct the violation:

List<Object> list = new ArrayList<Object>();

Why should the latter with List be used instead of ArrayList?

解决方案

Using interfaces over concrete types is the key for good encapsulation and for loose coupling your code.

It's even a good idea to follow this practice when writing your own APIs. If you do, you'll find later that it's easier to add unit tests to your code (using Mocking techniques), and to change the underlying implementation if needed in the future.

Here's a good article on the subject.

Hope it helps!

这篇关于为什么应该优先选择Java类的接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆