如何使代码可重用?

发布于 2024-07-08 07:19:57 字数 196 浏览 6 评论 0原文

任何代码都可以以某种方式重用,至少如果您修改代码的话。 随机代码本身不太可重用。 当我读一些书时,他们通常说你应该通过考虑代码使用的其他情况来显式地使代码可重用。 但某些代码也不应该是一个无所不能的类。

我想要有可重用的代码,以后不必更改。 如何使代码可重用? 代码可重用的要求是什么? 可重用代码必须具备哪些内容,哪些内容是可选的?

Any code can be reused in a way or an other, at least if you modify the code. Random code is not very reusable as such. When I read some books, they usually say that you should explicitly make the code reusable by taking into account other situations of code usage too. But certain code should not be an omnipotent all doing class either.

I would like to have reusable code that I don't have to change later. How do you make code reusable? What are the requirements for code being reusable? What are the things that reusable code should definitely have and what things are optional?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

笛声青案梦长安 2024-07-15 07:19:57

请参阅编写可重用代码的 10 个技巧寻求一些帮助。

  1. 保持代码干燥。 Dry 的意思是“不要重复自己”。
  2. 让一个类/方法只做一件事。
  3. 为您的课程编写单元测试并使测试课程变得容易。
  4. 从任何框架代码中删除业务逻辑或主要代码
  5. 尝试更抽象地思考并使用接口和抽象类。
  6. 扩展代码。 编写将来可以轻松扩展的代码。
  7. 不要编写不需要的代码。
  8. 尝试减少耦合。
  9. 更加模块化
  10. 编写代码,就像您的代码是外部 API 一样

See 10 tips on writing reusable code for some help.

  1. Keep the code DRY. Dry means "Don't Repeat Yourself".
  2. Make a class/method do just one thing.
  3. Write unit tests for your classes AND make it easy to test classes.
  4. Remove the business logic or main code away from any framework code
  5. Try to think more abstractly and use Interfaces and Abstract classes.
  6. Code for extension. Write code that can easily be extended in the future.
  7. Don't write code that isn't needed.
  8. Try to reduce coupling.
  9. Be more Modular
  10. Write code like your code is an External API
っ〆星空下的拥抱 2024-07-15 07:19:57

如果您采用测试驱动开发方法,那么您的代码只能在基于即将出现的场景进行重构时才可重用。

就我个人而言,我发现不断重构会产生更清晰的代码,而不是试图事后猜测我需要为特定类编写哪些场景。

If you take the Test-Driven Development approach, then your code only becomes re-usable as your refactor based on forthcoming scenarios.

Personally I find constantly refactoring produces cleaner code than trying to second-guess what scenarios I need to code a particular class for.

杀お生予夺 2024-07-15 07:19:57

最重要的是,可维护性使代码可重用。

可重用性本身并不是一个有价值的目标。 相反,它是编写结构良好、易于维护且有用的代码的副产品。

如果您打算编写可重用的代码,您经常会发现自己试图考虑未来项目中可能需要的行为要求。 无论您在这方面做得多么出色,您都会发现您对这些面向未来的要求的理解是错误的。

另一方面,如果您从当前项目的裸需求开始,您会发现您的代码可以干净、紧凑且优雅。 当您正在处理另一个需要类似功能的项目时,您自然会调整原始代码。

我建议查看您选择的编程语言/范例的最佳实践(例如 Java/C# 类型的模式和 SOLID)、精益/敏捷编程文献,以及(当然)《Code Complete》一书。 了解这些方法的优点和缺点将无止境地提高你的编码实践。 然后,您的所有代码都将变得可重用 - 但“偶然”,而不是设计使然。

另请参阅此处:编写可维护的代码

More than anything else, maintainability makes code reusable.

Reusability is rarely a worthwhile goal in itself. Rather, it is a by-product of writing code that is well structured, easily maintainable and useful.

If you set out to make reusable code, you often find yourself trying to take into account requirements for behaviour that might be required in future projects. No matter how good you become at this, you'll find that you get these future-proofing requirements wrong.

On the other hand, if you start with the bare requirements of the current project, you will find that your code can be clean and tight and elegant. When you're working on another project that needs similar functionality, you will naturally adapt your original code.

I suggest looking at the best-practices for your chosen programming language / paradigm (eg. Patterns and SOLID for Java / C# types), the Lean / Agile programming literature, and (of course) the book "Code Complete". Understanding the advantages and disadvantages of these approaches will improve your coding practice no end. All your code will then become reausable - but 'by accident', rather than by design.

Also, see here: Writing Maintainable Code

心房敞 2024-07-15 07:19:57

当编写一个相对较大的项目时,您将编写各种模块(部分)。 实践中的可重用代码意味着您将创建需要相同功能的其他项目可以使用的库。

所以,你必须确定可以重用的模块,为此

  1. 确定每个模块的核心能力。 例如,如果您的项目必须压缩文件,您将有一个处理文件压缩的​​模块。 不要让它做的事情超过一件事。 只有一件事。

  2. 编写一个库(或类)来处理文件压缩,除了要压缩的文件、输出和压缩格式之外不需要任何其他东西。 这将使模块与项目的其余部分分离,使其能够在不同的设置中(重新)使用。

  3. 您不必第一次就让它完美,当您实际重用该库时,您可能会发现设计中的缺陷(例如,您没有使其模块化到足以添加新的压缩)轻松格式化),您可以第二次修复它们并提高模块的可重用性。 你重用它的次数越多(并修复缺陷),它就越容易重用。

最重要的是要考虑的是解耦,如果你编写紧耦合的代码,重用性是第一个受害者。

将所有需要的状态或上下文保留在库之外。 添加方法来指定库的状态。

You'll write various modules (parts) when writing a relatively big project. Reusable code in practice means you'll have create libraries that other projects needing that same functionality can use.

So, you have to identify modules that can be reused, for that

  1. Identify the core competence of each module. For instance, if your project has to compress files, you'll have a module that will handle file compression. Do NOT make it do more than ONE THING. One thing only.

  2. Write a library (or class) that will handle file compression, without needing anything more than the file to be compressed, the output and the compression format. This will decouple the module from the rest of the project, enabling it to be (re)used in a different setting.

  3. You don't have to get it perfect the first time, when you actually reuse the library you will probably find out flaws in the design (for instance, you didn't make it modular enough to be able to add new compression formats easily) and you can fix them the second time around and improve the reusability of your module. The more you reuse it (and fix the flaws), the easier it'll become to reuse.

The most important thing to consider is decoupling, if you write tightly coupled code reusability is the first casualty.

Leave all the needed state or context outside the library. Add methods to specify the state to the library.

野却迷人 2024-07-15 07:19:57

对于“重用”的大多数定义来说,代码重用是一个神话,至少根据我的经验。 你能看出我有一些伤疤吗? :-)

通过重用,我并不是指获取现有的源文件并将其提交,直到出现新的组件或服务。 我的意思是采用特定的组件或服务并在不进行更改的情况下重复使用它。

我认为第一步是让自己形成一种心态,即至少需要 3 次迭代才能创建可重用组件。 为什么是3? 因为当你第一次尝试重用一个组件时,你总是会发现它无法处理的东西。 那么你必须改变它。 这种情况会发生几次,直到最终您拥有一个至少看起来可以重用的组件。

另一种方法是进行昂贵的前瞻性设计。 但成本都是预先确定的,而收益(可能)会在一段时间内显现出来。 如果你的老板坚持认为当前的项目进度始终占主导地位,那么这种方法就行不通。

For most definitions of "reuse", reuse of code is a myth, at least in my experience. Can you tell I have some scars from this? :-)

By reuse, I don't mean taking existing source files and beating them into submission until a new component or service falls out. I mean taking a specific component or service and reusing it without alteration.

I think the first step is to get yourself into a mindset that it's going to take at least 3 iterations to create a reusable component. Why 3? Because the first time you try to reuse a component, you always discover something that it can't handle. So then you have to change it. This happens a couple of times, until finally you have a component that at least appears to be reusable.

The other approach is to do an expensive forward-looking design. But then the cost is all up-front, and the benefits (may) appear some time down the road. If your boss insists that the current project schedule always dominates, then this approach won't work.

猫七 2024-07-15 07:19:57

面向对象允许您将代码重构为超类。 这也许是最简单、最便宜和最有效的再利用方式。 普通的类继承不需要过多考虑“其他情况”; 您不必构建“全能”代码。

除了简单的继承之外,重用是你发现的而不是你发明的。 当您想要重用自己的包之一来解决略有不同的问题时,您会遇到重用情况。 当你想重用一个不完全适合新情况的包时,你有两种选择。

  1. 复制它并修复它。 您现在必须使用几乎相似的软件包——这是一个代价高昂的错误。

  2. 使原始包在两种情况下可重用。

这样做只是为了重用。 而已。 过多地考虑“潜在”重用和未定义的“其他情况”可能会浪费时间。

Object-orientation allows you to refactor code into superclasses. This is perhaps the easiest, cheapest and most effective kind of reuse. Ordinary class inheritance doesn't require a lot of thinking about "other situations"; you don't have to build "omnipotent" code.

Beyond simple inheritance, reuse is something you find more than you invent. You find reuse situations when you want to reuse one of your own packages to solve a slightly different problem. When you want to reuse a package that doesn't precisely fit the new situation, you have two choices.

  1. Copy it and fix it. You now have to nearly similar packages -- a costly mistake.

  2. Make the original package reusable in two situations.

Just do that for reuse. Nothing more. Too much thinking about "potential" reuse and undefined "other situations" can become a waste of time.

谁与争疯 2024-07-15 07:19:57

其他人已经提到过这些策略,但这里是正式的。 这三个将使您走得更远:

  • 遵守单一责任
    原则
    - 它确保您的类只“做一件事”,这意味着它更有可能被包含相同内容的另一个应用程序重用。
  • 遵守里氏法则
    替换原则
    - 它确保您的代码“毫无意外地执行预期的操作”,这意味着它更有可能被另一个需要完成相同操作的应用程序重用。
  • 遵守开放/封闭原则 - 它确保您的代码可以表现出不同的行为无需修改其源代码,这意味着无需直接修改即可重用。

Others have mentioned these tactics, but here they are formally. These three will get you very far:

  • Adhere to the Single Responsibility
    Principle
    - it ensures your class only "does one thing", which means it's more likely it will be reusable for another application which includes that same thing.
  • Adhere to the Liskov
    Substitution Principle
    - it ensures your code "does what it's supposed without surprises", which means it's more likely it will be reusable for another application that needs the same thing done.
  • Adhere to the Open/Closed Principle - it ensures your code can be made to behave differently without modifying its source, which means it's more likely to be reusable without direct modification.
北座城市 2024-07-15 07:19:57

要添加到上述项目中,我想说:

  • 使这些函数成为您需要重用的通用
  • 函数 使用配置文件并使代码使用 files/db 中定义的属性
  • 明确地将您的代码分解为那些提供独立功能的函数/类功能,可以在不同的场景中使用,并使用配置文件定义这些场景

To add to the above mentioned items, I'd say:

  • Make those functions generic which you need to reuse
  • Use configuration files and make the code use the properties defined in files/db
  • Clearly factor your code into such functions/classes that those provide independent functionality and can be used in different scenarios and define those scenarios using the config files
云裳 2024-07-15 07:19:57

我会添加“类组合优于类继承”的概念(源自此处的其他答案)。
这样,“组合”对象不关心它所依赖的对象的内部结构 - 只关心它的行为,这会导致更好的封装和更容易的可维护性(测试,需要关心的细节更少)。
在 C# 和 Java 等语言中,它通常至关重要,因为没有多重继承,因此它有助于避免您可能遇到的继承图地狱。

I would add the concept of "Class composition over class inheritance" (which is derived from other answers here).
That way the "composed" object doesn't care about the internal structure of the object it depends on - only its behavior, which leads to better encapsulation and easier maintainability (testing, less details to care about).
In languages such as C# and Java it is often crucial since there is no multiple inheritance so it helps avoiding inheritance graph hell u might have.

昨迟人 2024-07-15 07:19:57

如前所述,模块化代码比非模块化代码更具可重用性。

帮助实现模块化代码的一种方法是使用封装,请参阅此处的封装理论:
http://www.edmundkirwan.com/

Ed。

As mentioned, modular code is more reusable than non-modular code.

One way to help towards modular code is to use encapsulation, see encapsulation theory here:
http://www.edmundkirwan.com/

Ed.

不知所踪 2024-07-15 07:19:57

避免重新发明轮子。 就是这样。 这本身就有上面提到的许多好处。 如果您确实需要更改某些内容,那么您只需创建另一段代码、另一个类、另一个常量、库等...它可以帮助您和在同一应用程序中工作的其他开发人员。

Avoid reinventing the wheel. That's it. And that by itself has many benefits mentioned above. If you do need to change something, then you just create another piece of code, another class, another constant, library, etc... it helps you and the rest of the developers working in the same application.

谜兔 2024-07-15 07:19:57

注释,详细,当你下次再看代码时,所有看起来可能会令人困惑的地方。 过于冗长的注释可能会有点烦人,但它们比稀疏的注释要好得多,并且可以节省数小时的时间来试图弄清楚你上次在做什么。

Comment, in detail, everything that seems like it might be confusing when you come back to the code next time. Excessively verbose comments can be slightly annoying, but they're far better than sparse comments, and can save hours of trying to figure out WTF you were doing last time.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文