为什么应该首选 Java 类的接口? [英] Why should the interface for a Java class be preferred?

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

问题描述

PMD 会报告以下违规行为:

PMD would report a violation for:

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

违规是避免使用像'ArrayList'这样的实现类型;改用接口".

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>();

为什么应该使用带有 List 的后者而不是 ArrayList?

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.

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

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.

这是一篇好文章主题.

希望能帮到你!

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

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