你应该总是在Java中编写代码 [英] Should you always Code To Interfaces In Java

查看:118
本文介绍了你应该总是在Java中编写代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解了编码到接口的原理 - 将实现与接口分离,并允许接口的实现被交换出来。



我应该为我写的每一个类别的接口进行编码,还是那些过度使用?我不想将项目中的源文件数量加倍,除非真的值得。



可以使用什么因素来决定是否通过界面进行代码?



但是,事先知道未来会发生什么变化并不容易,特别是如果您没有经验的话。我认为这个问题的解决方案是重构:只要不需要,保持简单(=无接口)。当需要时,只需执行介绍/提取界面重构(几乎所有体面的IDE都支持)。



当您执行此操作时,仅提取呼叫者实际需要的那些方法。不要害怕提取多个单独的接口(如果并非所有提取的方法都是一致的)。



重构的一个驱动程序可能是测试:如果你不能轻易地测试一些类,只考虑引入一个/一些接口。这也将允许您使用嘲笑,这可能会在许多情况下大大简化测试。



编辑:基于Tarski的评论我已经意识到更重要的场景/对以前语句的调整:

如果您提供外部API(对于其他[sub]项目,或者真正将其释放到野外),然后使用API​​中的接口(除简单的价值类)几乎总是一个好主意。

它将允许您改变impl,如果你喜欢,而不打扰客户端代码。只有当您还需要更改界面时,您将会遇到问题。不破坏兼容性将非常棘手(如果不是不可能)。


I understand the principles of Coding to Interfaces - to decouple the implementation from the interface, and to allow implementations of the interface to be swapped in and out.

Should I code to interfaces for every class I write or is that overkill? I don't want to double the number of source files in a project unless it's really worth it.

What factors can I use to decide whether to code by interface or not?

解决方案

In general I agree with the other answers: use an interface when you know or anticipate change and/or different implementation, or go for testability.

But it's not always easy to know in advance what may change in the future, especially if you are not so experienced. I think the solution for that problem is refactoring: keep it simple (= no interface) as long as it is not needed. When the need arises simply do an "Introduce/Extract interface" refactoring (supported by almost all decent IDEs).

When you do it extract only those methods that are actually needed by the callers. Don't be afraid to extract more then one separate interfaces (if not all of the extracted methods are really coherent).

One driver of the refactoring might be the testing: if you can't easily test something with classes only consider introducing one/some interface(s). This will also allow you to use mocking which may greatly simplify testing in many cases.

Edit: based on Tarski's comment I've realized one more important scenario/adjustment to the previous statements:
If you provide an external API (for other [sub]projects, or really release it "to the wild") then using interfaces in the API (except for simple value classes) is almost always a good idea.
It will allow you to change the impl if you like without disturbing the client code. You will have a problem only if you also have to change the interface. Not breaking compatibility will be very tricky (if not impossible).

这篇关于你应该总是在Java中编写代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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