你应该总是用 Java 编写接口代码吗 [英] Should you always Code To Interfaces In Java

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

问题描述

我了解编码到接口的原则 - 将实现与接口分离,并允许接口的实现交换进出.

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.

我可以使用哪些因素来决定是否按接口编码?

推荐答案

总的来说,我同意其他答案:当您知道或预期更改和/或不同的实现时使用接口,或者寻求可测试性.

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.

但预先知道未来可能会发生什么变化并不总是那么容易,尤其是如果您没有那么有经验的话.我认为该问题的解决方案是重构:只要不需要,就保持简单(= 没有接口).当需要时,只需进行引入/提取接口"重构(几乎所有像样的 IDE 都支持).

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.

根据 Tarski 的评论,我意识到了一个更重要的场景/对先前陈述的调整:
如果您提供外部 API(用于其他 [子] 项目,或者真正将其公开"),那么在 API 中使用接口(简单值类除外)几乎总是一个好主意.
如果您愿意,它将允许您在不干扰客户端代码的情况下更改 impl.仅当您还必须更改接口时,您才会遇到问题.不破坏兼容性将非常棘手(如果不是不可能的话).

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天全站免登陆