# 第29条：考虑包装扩展 API

大量使用不稳定的 API 是有风险的，无论是当创造者阐明它是不稳定，还是我们不相信创造者能保持它的稳定。记住，如果 API 不可避免地发生变化，我们需要调整每一次的使用，并应该考虑限制使用它，尽可能地将它与我们的逻辑分离开。这就是为什么我们经常在自己的项目中包装可能不稳定的外部库 api。 这样做会给我们更多的自由和稳定性：

* 我们不害怕 API 的改变，因为我们只需要改变包装类内部的用法
* 我们可以根据项目风格和逻辑来调整 API
* 如果这个库有问题，我们可以用别的库来替换它
* 如果需要的话，我们可以改变这些对象的行为（当然了，这样做要担负起责任）

也有人会反对这种做法：

* 我们需要为所有这些库都定义包装类
* 我们包装的 API 是内部的， 一些开发人员为了看懂我们的项目，必须要去学习它
* 没有教程讲解我们的内部 API 如果工作，我们也不应该期待答案会出现在 Stack Overflow 上

综上所述，你需要决定应该包装哪些 api，告诉我们一个库有多稳定的一个很好的方式是版本号和用户数量，一般来说，库的用户数越多，库就越稳定。当库开发者知道他们小的变化可能影响到多个项目时，他们对更改就会更加小心。风险最多的库是那些不怎么受欢迎的新库，明智地使用他们，并考虑将它们包装到你自己的类和函数中，以便在内部控制它们。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://rikka-2.gitbook.io/effective-kotlin-zhong-wen-ban/good-design/di-si-zhang-chou-xiang-she-ji/di-29-tiao-kao-lv-bao-zhuang-kuo-zhan-api.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
