Functions are an essential ingredient of all programs, large and small, and serve as our primary medium to express computational processes in a programming language. So far, we have discussed the formal properties of functions and how they are applied. We now turn to the topic of what makes a good function. Fundamentally, the qualities of good functions all reinforce the idea that functions are abstractions.
函数是所有程序的重要组成部分,无论大小,并且作为我们用编程语言表达计算过程的主要媒介。到目前为止,我们已经讨论了函数的形式属性以及它们是如何应用的。现在我们来谈谈,怎样才能构成一个好的函数。从根本上说,优秀函数的特性都强化了函数是抽象的观念。
Each function should have exactly one job. That job should be identifiable with a short name and characterizable in a single line of text. Functions that perform multiple jobs in sequence should be divided into multiple functions.
每个函数应该只有一个任务。这个任务应该可以用一个简短的名字来识别,并且可以用一行文字来描述。按顺序执行多项任务的函数应该划分为多个函数。
Don’t repeat yourself is a central tenet of software engineering. The so-called DRY principle states that multiple fragments of code should not describe redundant logic. Instead, that logic should be implemented once, given a name, and applied multiple times. If you find yourself copying and pasting a block of code, you have probably found an opportunity for functional abstraction.
不要重复劳动(DRY)是软件工程的一个中心原则。所谓的DRY是指代码的多个片段不应该描述冗余逻辑。相反,该逻辑应该只实现一次,给定一个名称,并应用多次。如果您发现自己在复制和粘贴一段代码,那么您可能已经找到了函数抽象的机会。
Functions should be defined generally. Squaring is not in the Python Library precisely because it is a special case of the pow function, which raises numbers to arbitrary powers.
函数应该定义地普遍一些。Python库中没有平方,正是因为它是pow函数的特例,pow函数将数字提升到任意次幂。
These guidelines improve the readability of code, reduce the number of errors, and often minimize the total amount of code written. Decomposing a complex task into concise functions is a skill that takes experience to master. Fortunately, Python provides several features to support your efforts.
这些指导方针提高了代码的可读性,减少了错误的数量,并且常常使编写的代码总量最小化。将复杂的任务分解为简洁的函数是一项需要经验来掌握的技能。幸运的是,python 提供了几个特性来支持您的工作。