简体   繁体   English

将类添加到第三方依赖项/程序包是不好的做法吗? (java)

[英]Is it bad practice to add a class to a third party dependency/package? (java)

I have an interaction client from a 3rd party dependency for a service I need to use. 我有一个来自第三方依赖项的交互客户端,需要使用我提供的服务。 Some of the behaviors don't fit my use case and I want to try to extend or just rewrite an adapter for it, but a lot of the methods or variables I need are protected. 有些行为不适合我的用例,我想尝试扩展或只是为其重写适配器,但是我需要的许多方法或变量都受到了保护。 Should I just write a class that belongs in that package to access those? 我应该只编写一个属于该软件包的类来访问那些类吗? I haven't ever heard it explicitly stated not to, but it seems to defeat the purpose of having a package in the first place. 我从来没有听过它明确声明不这样做,但是这似乎挫败了首先拥有一个软件包的目的。

I would say it's a very bad idea. 我会说这是一个非常糟糕的主意。 You should never, ever modify a 3rd party JAR in any way. 您绝不应该以任何方式修改第三方JAR。 You're better off to consider them sealed. 您最好考虑将它们密封。

The reason is two-fold: 原因有两个:

  1. You may break the dependency code. 您可能会破坏依赖性代码。
  2. The moment you modify that 3rd party JAR you have to modify every update in the same way. 修改第3方JAR的那一刻,您必须以相同的方式修改每个更新。

You are free to extend a third party class, as long as it's not marked as final . 您可以自由扩展第三方类,只要它没有被标记为final But it'll be part of your code if you do that. 但这将成为代码的一部分。 You are free to pull in a new version of that 3rd party JAR any time it's available. 您可以随时使用该第三方JAR的新版本。

If the methods and variables are protected, you can extend the class with your own implementation. 如果方法和变量受保护,则可以使用自己的实现扩展该类。 The child class is able to access the parent class's protected variables and properties. 子类能够访问父类的受保护变量和属性。

Your implementation does not need to be in the same package. 您的实现无需位于同一软件包中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM