代码可读性_超越了源代码的可读性和理解

代码可读性

The “Beyond the Source Code” series of posts will explore source code beyond its use as a set of instructions that direct a process or set of processes. We will dive in topics such as readability, metaprogramming, quines, and many other topics that look at source code in a different light. The motivation for this series comes from the idea of making source code work for developers, rather than the developers having to work against the source code.

“超越源代码”系列文章将探讨源代码,而不是将其用作指导一个过程或一组过程的指令集。 我们将探讨诸如可读性,元编程,quines之类的主题,以及许多其他以不同的眼光看待源代码的主题。 本系列的动机来自使开发人员可以使用源代码的想法,而不是开发人员必须对源代码进行工作。

In this particular post we will be exploring the readability of source code and the implications of having high readability vs low readability. We will also explore how certain programs can interpret source code and automatically build documentation to improve developer productivity. Keep in mind that readability is a completely arbitrary metric and easy-to-read code in one person’s eyes may be completely different than another’s opinion.

在这篇特别的文章中,我们将探讨源代码的可读性以及具有高可读性与低可读性的含义。 我们还将探讨某些程序如何解释源代码并自动构建文档以提高开发人员的生产力。 请记住,可读性是一种完全任意的度量标准,一个人眼中易于阅读的代码可能与另一个人的观点完全不同。

过去的快速旅行 (A Quick Trip to the Past)

In the 1830s, a man by the name of Charles Babbage invented a device called the Analytical engine. The analytical engine was a by-product of every engineer’s constant desire to optimize, as it was devised during the development of an earlier project, the Difference Engine. Some things never change right? An engineer realizing during a project that a better version of the project is possible! That constant desire for improvement and optimization can be seen in engineers and programmers today, and it was no different back then. The Difference Engine was a highly focused mathematical tool, while the design for the Analytical Engine introduced a much more generalized computer. This tantalizing possibility of generalized computing and a headwind of problems while building the Difference Engine made Babbage drop the project and pursue the Analytical Engine. And just like a common scenario that happens many times in today’s world, funding became a problem, disagreements were had, and the project was never completed. HOWEVER, the design of the project was still used as a basis for the world’s first computer programs.

在1830年代,一个名叫查尔斯·巴贝奇(Charles Babbage)的人发明了一种称为分析引擎的设备。 正如在早期项目“差异引擎”的开发过程中所设计的那样,分析引擎是每个工程师不断追求优化的副产品。 有些事情永远不会改变,对吧? 工程师在项目执行过程中意识到可能会有更好的项目版本! 如今,工程师和程序员可以看到对改进和优化的不断渴望,这与当时没什么不同。 差异引擎是高度集中的数学工具,而分析引擎的设计引入了更为通用的计算机。 在构建差分引擎时,这种通用计算的诱人可能性和问题的逆风使巴贝奇放弃了该项目,而继续追求分析引擎。 就像当今世界上多次发生的常见情况一样,资金成为问题,出现了分歧,并且该项目从未完成。 但是,该项目的设计仍被用作世界上第一个计算机程序的基础。

The Analytical Engine was a more generalized computer capable of processing “programs” on punch cards to calculate arithmetic formulae and problems. These punch cards can be seen as the first instances of source code, and each individual punched hole contributed to an instruction for the computer, akin to modern programming languages’ functions, keywords, and expressions. Now we introduce a new character to the story. Augusta Ada King, countess of Lovelace, commonly known as Ada Lovelace, worked on the Analytical Engine, and saw the true potential of the machine beyond the punchcards and complex machinery. She realized that computation was more than reproducing mathematical calculations, but could be used as a means of describing a more complex set of instructions to solve larger problems. This realization was seen in her notes to Babbage where she describes a method for calculating Bernoulli’s numbers.

分析引擎是一种更通用的计算机,能够处理打Kong卡上的“程序”以计算算术公式和问题。 这些打Kong卡可以看作是源代码的第一个实例,每个打Kong都为计算机指令做出了贡献,类似于现代编程语言的功能,关键字和表达式。 现在我们为这个故事介绍一个新角色。 Lovelace伯爵夫人(俗称Ada Lovelace)的奥古斯塔·阿达·金(Augusta Ada King)从事分析引擎的研究,发现了机器的真正潜力超越了打Kong卡和复杂的机器。 她意识到,计算不仅仅是重现数学计算,还可以用作描述一组更复杂的指令以解决更大问题的手段。 她在给巴贝奇的笔记中看到了这种认识,在那里她描述了一种计算伯努利数的方法。

“I want to put in something about Bernoulli’s Numbers, in one of my Notes, as an example of a how an implicit function may be worked out by the engine, without having been worked out by human head and hands first…”

“我想在我的一份笔记中加入有关伯努利数字的内容,作为一个示例,说明如何在不先人工操作的情况下由引擎处理隐式函数……”

— Ada Lovelace to Charles Babbage

—艾达·洛夫雷斯(Ada Lovelace)对查尔斯·巴贝奇(Charles Babbage)

These notes described the world’s first algorithm to be carried out by a computer. In a humorous way, Ada Lovelace even exhibits her frustration with the number algorithm in one of her notes.

这些说明描述了世界上第一个由计算机执行的算法。 Ada Lovelace以幽默的方式甚至在她的笔记之一中表现出对数字算法的沮丧。

“My Dear Babbage . I am in much dismay at having got into so amazing a quagmire and botheration with these Numbers, that I cannot possibly get the thing done today…”

“亲爱的巴贝奇。 我对这些数字陷入了如此惊人的泥潭和困扰,感到非常沮丧,以至于我今天无法完成任务……”

— Ada Lovelace to Charles Babbage

—艾达·洛夫雷斯(Ada Lovelace)对查尔斯·巴贝奇(Charles Babbage)

As a developer, I think I will use this line with my boss the next time I am impeded by a massive bug.

作为开发人员,我认为下一次遇到大量错误时,我将与老板一起使用这条线。

My Dear Supervisor. I am in much dismay at having into so amazing a quagmire and botheration with this segmentation fault, that I cannot possibly get the thing done today…”

我亲爱的主管。 对于这种分割错误,我陷入了如此惊人的泥潭和困扰,我感到非常沮丧,以至于我今天无法完成任务……”

The punch cards, due to their inherent simple atomic nature with being simple holes on a piece of material, were very difficult to be interpret by a human. This is why Ada Lovelace put so much thought into the description of the algorithm and why the notes were so verbose. Not only was she the world’s first programmer, she was also a shining example of a developer that creates excellent documentation. An example of a program that could be computed on the Analytical Engine is seen below.

打Kong卡由于其固有的简单原子性质以及在一块材料上的简单Kong洞而很难被人解释。 这就是为什么Ada Lovelace在算法描述中投入如此多的思想,以及为什么注释如此冗长的原因。 她不仅是世界上第一个程序员,而且还是开发出色文档的开发人员的光辉榜样。 下面显示了可以在分析引擎上计算的程序示例。

If you look closely, you can see inscriptions on each of these cards. What could these be, but perhaps some of the first code comments ever written?

如果仔细观察,您会在每张卡片上看到铭文。 这些可能是什么,但是也许有史以来最初的一些代码注释?

Fast-forward a century, and you can see the same ideas coming to light with the likes of Alan Turing, Von Neumann, and others working towards more generalized computing and ways to efficiently execute arbitrary algorithms on machines. Throughout the evolution of computing, one concept persisted however, and that is that programs could only be interpreted by programmers, mathematicians, and engineers. The concept of programming is a difficult one since it is the complete breakdown of a process and providing logical order and steps that a computer, a dumb machine incapable of thought (for now, anyway), can piece together and execute to a meaningful conclusion. However, this started to change later in the century when computer scientists wanted to start bridging the gap between technology and business.

快进一个世纪,您会看到与Alan Turing,Von Neumann等人一样的想法逐渐浮出水面,这些人致力于更通用的计算以及有效地在机器上执行任意算法的方法。 在整个计算的发展过程中,一个概念一直存在,那就是程序只能由程序员,数学家和工程师来解释。 编程的概念是一个困难的概念,因为它是一个过程的完整分解,并提供逻辑顺序和步骤,计算机(一台无法思考的笨拙的机器)(无论如何现在)可以拼凑起来并执行有意义的结论。 但是,这种情况在本世纪晚些时候开始改变,当时计算机科学家希望开始弥合技术与业务之间的鸿沟。

Enter COBOL, or “common business-oriented language”. Still used in ~80% of today’s business transactions, COBOL was designed to perform business-focused functions such as financial, administrative, and data-focused functions fast, and be easy to work with. This “easy to work with” concept was fairly new. When looking at the syntax of COBOL, it uses plain English words to describe operations such as: FOR, COMPUTE, DISPLAY, PERFORM, MOVE, SUBTRACT. This use of English words was intentional, in the hopes that business-minded individuals with domain expertise would be able to pickup the source code and understand it, either to contribute to or validate a developer’s work. This move towards readability received high praise in the business world, however the verbosity of the language turns many developers off, as it has an impact on developer efficiency, succinctness of programs, and “noise” when reviewing the code.

输入COBOL或“面向企业的通用语言”。 COBOL仍被用于当今约80%的业务交易中,旨在快速执行且易于使用的,以业务为中心的功能,例如财务,管理和以数据为中心的功能。 这种“易于使用”的概念还很新。 在查看COBOL的语法时,它使用简单的英语单词来描述以下操作:FOR,COMPUTE,DISPLAY,PERFORM,MOVE,SUBTRACT。 英文单词的这种使用是有意的,希望具有领域专业知识的具有业务头脑的个人能够获取源代码并理解它,从而有助于或验证开发人员的工作。 迈向可读性的这一举动在商业界赢得了高度赞扬,但是语言的冗长性使许多开发人员望而却步,因为它会影响开发人员的效率,程序的简洁性以及在检查代码时的“噪音”。

Programming languages have since moved in a variety of directions. Some languages emphasize readability and understanding (Visual Basic, Python, Ruby), some focus on performance (C++, Rust, Go), and some are just plain nutty (Brainf**k, Befunge, Malbolge). Regardless of the direction of a programming language, as long as its intended purpose is widespread usage in a project, readability and understanding always have to be taken into consideration. We will now look at some methods for how readability and understanding in source code can be improved, and finally how source code can be taken a step further and given an opportunity to speak for itself.

此后,编程语言已朝着各个方向发展。 有些语言强调可读性和理解力(Visual Basic,Python,Ruby),有些注重性能(C ++,Rust,Go),有些则只是简单的坚果(Brainf ** k,Befunge,Malbolge)。 无论编程语言的方向如何,只要其预期目的在项目中得到广泛使用,就必须始终考虑可读性和理解性。 现在,我们将研究一些方法,这些方法可以改善源代码的可读性和理解力,最后可以使源代码更进一步,并有机会自己说出来。

自我证明代码 (Self-Documenting Code)

Self-documenting code follows the idea that fewer comments and documentation is needed if the code is able to “speak for itself.” The concept favors the use of more descriptive variable names, less obscure syntax usage, and following conventions for code styling. Although the concept is powerful when used in conjunction with another method of sharing knowledge, self-documenting code can fall flat if taken to extremes.

自记录代码遵循这样的想法,即如果代码能够“自己说话”,则需要较少的注释和文档。 该概念支持使用更具描述性的变量名,较少模糊的语法用法以及遵循代码样式约定。 尽管该概念与另一种共享知识的方法结合使用时功能强大,但如果将自我记录代码极端化,则可能会陷入僵局。

Verbose variable names can be great so that other developers can pickup source code and understand it, however this can become extreme if you have variable names like these:

详细的变量名非常有用,以便其他开发人员可以获取源代码并理解它,但是如果您具有以下变量名,则这可能变得极端:

customer_shopping_cart_item_size = 10
customer_is_currently_shopping = True
customer_checkout_successful = True
current_order_street_address_1 = "1313 Mockingbird Lane"

The above variable naming is extremely verbose and easy to understand, but I pity the developer that has to constantly read the source code or type these variable names over and over again. And if you are one of these developers, I strongly recommend purchasing a more ergonomic keyboard. Instead, the above variable names can be succinctly declared like so:

上面的变量命名非常冗长且易于理解,但是我很遗憾开发人员必须不断读取源代码或一遍又一遍地键入这些变量名。 如果您是这些开发人员之一,我强烈建议您购买更符合人体工程学的键盘。 而是可以像上面这样简洁地声明上面的变量名:

cust_cart_size = 10
cust_is_shopping = True
cust_chkout_success = True
ord_streetaddr_1 = "1313 Mockingbird Lane"

These are just examples of how the variable names could be shortened without losing meaning. Just be careful not to go to the extreme of variable name abbreviation:

这些只是如何在不失去含义的情况下缩短变量名的示例。 请注意不要太过夸张地使用变量名缩写:

c_crt_sz = 10
is_c_shop = True
chk_ok = True
o_saddr1 = "1313 Mockingbird Lane"

The naming should lie somewhere between a business manager definition and the computer from Space Odyssey declaring it.

命名应介于业务经理定义和Space Odyssey声明的计算机之间。

Self-documenting code is a great approach to improving readability and understanding of source code, but should not be taken to extremes and used exclusively. Variable naming conventions, a common code styling guide, and best practice for syntax usage can all contribute to a more easy to understand code base, when paired with accompanying documentation and comments.

自记录代码是提高可读性和对源代码的理解的一种很好的方法,但是不应将其极端化,只能将其单独使用。 当与随附的文档和注释一起使用时,变量命名约定,通用的代码样式指南以及语法用法的最佳实践都可以使代码库更易于理解。

注释 (Comments)

Ah, the often forgotten code comment. The bane of computer science students everywhere, and the left-behind code artifact of developers far and wide. Comments are peculiar creature, as they can either be tomes to a future self, or a half-baked quip attempting to explain the use of a complex semaphore to fresh junior developer. If used properly, and frequently, comments provide a “close-to-the-metal” source of knowledge that will guide a developer as they traverse the code. They immediately surround the functionality they describe, so they are automatically provided context and reasoning within the code. In addition to this, they are the first thing developers write as they develop new code, so they are often the most accurate source of information when it comes to understanding “bare metal” functionality.

啊,经常被遗忘的代码注释。 到处都有计算机科学专业的学生的祸根,以及遍布各地的开发人员遗留的代码工件。 评论是一种奇特的生物,因为它们既可以是未来自我的书摘,也可以是半熟的讽刺小说,试图向新手初级开发者解释使用复杂的信号量。 如果使用得当且经常使用,注释将提供“最接近金属”的知识来源,它将指导开发人员遍历代码。 它们立即围绕着它们描述的功能,因此在代码内自动为它们提供了上下文和推理。 除此之外,它们是开发人员在开发新代码时首先编写的内容,因此在了解“裸机”功能时,它们通常是最准确的信息来源。

As seen in the quick trip to the past, comments have been around since the dawn of programming, and are met with various degrees of success. For example, an individual fresh to the world of punchcard programming would probably pickup a card, read the chicken scratch comment on the card and immediately GIVE UP trying to understand what is going on. The same can happen when you leave behind a comment that might be consumed by a fresh junior developer that has zero experience with the project. Comments should be used when the code is not straightforward, but should be used sparingly when the functionality can be easily understood by the code. For example:

从过去的快速旅行中可以看出,自编程之初就出现了注释,并获得了不同程度的成功。 例如,一个刚接触打Kong卡编程世界的人可能会拿起一张卡,阅读卡上的鸡刮痕注释,然后立即放弃尝试以了解发生了什么。 当您留下可能由对项目有零经验的新手初级开发人员使用的注释时,也会发生同样的情况。 当代码不直接时,应使用注释,但当代码易于理解功能时,应谨慎使用注释。 例如:

//The following sets the variable x to 10
x = 10

The above comment is pointless to somebody reading the source code. Any developer that is reading the source code that has familiarity with the syntax will immediately know what is happening with the variable declaration. However, in a case like the following, comments would be very welcome:

上面的注释对阅读源代码的人毫无意义。 任何正在阅读熟悉语法的源代码的开发人员都将立即知道变量声明正在发生什么。 但是,在以下情况下,非常欢迎发表评论:

y=[[x*100, x][x % 2 != 0] for x in range(1,11)]

The above line is a one-liner list comprehension that has “high information density” where a comment or two will allow any developer to understand what is going on.

上一行是具有“高信息密度”的单行列表理解,其中一两个注释将使任何开发人员都可以了解正在发生的事情。

Another area where comments are extremely valuable is showing the translation of a business concept to source code. Examples of communicating the translate of a business concept to code are: information access policies, financial calculations, administrative workflows. When translated into code, comments will explain to future developers where the computations originated from and the reasoning that went into them.

注释非常有价值的另一个领域是显示业务概念到源代码的转换。 传达业务概念到代码的转换的示例包括:信息访问策略,财务计算,管理工作流。 将注释转换为代码后,将向未来的开发人员解释计算的来源以及其中的原因。

超越源代码 (Beyond the Source Code)

What if the code could actually speak for itself with a smattering of self-documenting code and well-structured comments, and the outside help of an additional tool? This is where documentation generators come into play. A documentation generator is able to read source code in its entirety and extract out certain components, perform static analysis, and/or infuse hand-written documentation to create a body of knowledge ready to be published and consumed by others. Documentation generators can be designed to extract and document all the classes that exist in a project, the API (application programming interface) endpoints that exist, or the dependencies that the program relies on. These tools go beyond the source code by using the source code as data to help the code speak for itself and provide value back to the developer, beyond being a simple set of instructions.

如果该代码实际上可以用少量的自我文档化的代码和结构合理的注释来说明自己,那该怎么办? 这是文档生成器起作用的地方。 文档生成器能够完整地阅读源代码,并提取出某些组件,执行静态分析和/或注入手写文档来创建可供他人发布和使用的知识体系。 可以将文档生成器设计为提取和文档化项目中存在的所有类,存在的API(应用程序编程接口)端点或程序所依赖的依存关系。 这些工具超越了源代码,通过使用源代码作为数据来帮助代码说明自己并为开发人员提供价值,而不仅仅是一组简单的指令。

When working on a project as a sole developer, it can become tiresome to have to maintain the project, write all of the code, document the functionality, and manage deployments as well. By leveraging a documentation generator, a lone developer can leave the grunt work of formatting and maintenance to something that is built for grunt work and reproducibility. A program. The code becomes more than a simple “punchcard.” It becomes an artifact that is able to be used to solicit understanding and knowledge of the project and repeatedly provide easy-to-understand documentation.

当以唯一开发人员的身份从事项目工作时,必须维护项目,编写所有代码,记录功能并管理部署会变得很烦。 通过利用文档生成器,孤独的开发人员可以将繁琐的格式化和维护工作留给专为繁琐的工作和可再现性而构建的东西。 一个程序。 该代码不仅仅是一个简单的“打Kong卡”。 它成为一种工件,可以用来征求对项目的理解和知识,并反复提供易于理解的文档。

Large enterprises with distributed developer teams also benefit greatly from documentation generators. Hand-written documentation is difficult to maintain in a large group setting, however a documentation generator can be configured to continuously generate and publish updated documentation. As the source code is updated by the army of busy developers, the documentation is updated lockstep. This synchronicity between development and documentation guarantees accurate knowledge transfer, up-to-date training artifacts, and if the project is public-facing, a happier customer base since they will be continuously kept up-to-date on the latest and greatest.

具有分布式开发人员团队的大型企业还可以从文档生成器中受益匪浅。 手写文档很难在大型组中维护,但是可以将文档生成器配置为连续生成和发布更新的文档。 由于源代码由忙碌的开发人员进行更新,因此文档也随之更新。 开发与文档之间的这种同步性确保了准确的知识传递,最新的培训工件,并且如果项目是面向公众的,则将有一个更快乐的客户群,因为他们将不断保持最新和最大的状态。

下一步是什么? (What’s Next?)

We will continue to look behind the syntax and beyond the source code with quines. Quines are interesting programs that take zero input, and which carry out the sole functionality of outputting a copy of their own source code. Quines serve zero purpose, but provide a whimsical glimpse into the world of metaprogramming. Be sure to give me a follow to stay up-to-date and continue our journey beyond the source code.

我们将继续在语法后面,并在源代码之外加上quines。 Quines是有趣的程序,需要零输入,并且执行输出其自身源代码副本的唯一功能。 Quines服务于零目的,但提供了元编程世界的异想天开的一瞥。 一定要给我一个跟随,以保持最新,并继续我们的旅程,超越源代码。

文档生成器资源 (Documentation Generator Resources)

I have included a short listing of documentation generator resources that can provide great value to large projects. All of the following are open source.

我列出了可以为大型项目提供巨大价值的文档生成器资源的简短列表。 以下所有都是开源的。

Python (Python)

高朗 (Golang)

多种语言 (Multiple Languages)

翻译自: https://medium.com/@riptidedata/beyond-the-source-code-readability-and-understanding-ed6a214f9782

代码可读性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值