cssmagic / Learn-AI-Assisted-Python-Programming

📖 《AI 辅助编程 Python 实战》这本书的大本营。
142 stars 15 forks source link

[译] [302] 函数的益处 #37

Open cssmagic opened 8 months ago

cssmagic commented 8 months ago

3.2 Benefits of functions

3.2 函数的益处

We already mentioned that functions are critical in performing problem decomposition. Beyond problem decomposition, functions are valuable in software for a number of other reasons, including

我们之前提到,函数在进行问题拆解方面发挥着关键作用。其实,函数在软件开发中之所以宝贵,还源于其他诸多方面的原因,包括:

These benefits are huge for programmers. Programming languages haven’t always had functions. But even before they did, programmers did their best to use other features to mimic functions. They were ugly hacks (Google “goto statements” if you’re interested), and all programmers are happy that we have proper functions now.

这些益处对于程序员来说极为重要。编程语言并不是从一开始就内置了函数功能。但在函数功能出现之前,程序员们想尽办法使用其他特性来模拟函数的效果。那些替代方案往往显得笨拙(如果你感兴趣,不妨搜索“goto语句”来了解一下),而现在我们有了真正的函数,所有程序员都为之庆幸。

You may be asking, “I see how these advantages matter to humans, but how do they affect Copilot?” In general, we believe all the principles that apply to humans apply to Copilot, albeit sometimes for different reasons. Copilot may not have cognitive load, but it’s going to do better when we ask it to solve problems similar to what’s been done by humans before. Since humans write functions to solve tasks, Copilot will mimic that and write functions as well. Once we’ve written and tested a function, whether by hand or by Copilot, we don’t want to write it again. Knowing how to test if your program is working properly is just as essential for code produced by humans as it is by Copilot. Copilot is as likely to make mistakes when it generates code, so we want to catch those mistakes quickly, just as we do with human-written code. Even if you only work on your own code and never have anyone else read it, as programmers who have had to go back to edit code we wrote years ago, let us tell you that it is important for your code to be readable, even if the only person reading it is you.

你可能会好奇,“我理解这些好处对人类极为重要,但它们对 Copilot 有何影响?”总体而言,我们相信,所有适用于人类的原则也同样适用于 Copilot,尽管背后的原理可能有所不同。Copilot 固然没有认知负荷,但当我们要求它处理人类解决过的类似问题时,它的表现往往会更加出色。既然人类通过编写函数来完成任务,那 Copilot 也会很自然地仿效这一做法。一旦我们编写并测试了一个函数,不论是手写还是让 Copilot 来写,我们就不希望重复再写一遍了。要学会验证程序是否运行正常,不论是人类编写的代码还是 Copilot 生成的代码,这一点都至关重要。Copilot 在生成代码时同样可能犯错,因此我们希望能够迅速发现并修正这些错误,就像我们对待人类编写的代码一样。如果你只是在独立编写和维护自己的代码,从未让他人阅读过,也有必要关心可读性吗?作为曾不得不回顾和修改多年前自己编写的代码的程序员,我们想告诉你,保持代码的可读性非常重要,哪怕唯一的读者只有你自己。