Writing Maintainable Programs | 编写可维护程序

📚 Writing Maintainable Programs | 编写可维护程序

In Cambridge Computer Science courses, writing a program that merely works is not enough. Examiners expect you to demonstrate that your code can be read, understood, tested and modified by other programmers. This set of skills is called maintainability.

在剑桥计算机科学课程中,仅仅编写一个能够运行的程序是不够的。考官希望你展示你的代码能够被其他程序员阅读、理解、测试和修改。这套技能被称为可维护性。

This article explains the core techniques for writing maintainable programs, with a focus on pseudocode, structured programming and good practice required by Cambridge IGCSE and AS/A Level Computer Science.

本文解释编写可维护程序的核心技巧,重点放在剑桥 IGCSE 和 AS/A Level 计算机科学所要求的伪代码、结构化编程和良好实践上。


1. What is Maintainability? | 什么是可维护性?

Maintainability is the ease with which a program can be corrected, extended, understood or adapted after it has been written. A maintainable program is not just short or clever; it is clear, organised and predictable.

可维护性是指一个程序在编写完成后被纠正、扩展、理解或调整的容易程度。一个可维护的程序不只是简短或巧妙,而是清晰、有条理且可预测。

In examinations, marks are often awarded for using meaningful variable names, consistent indentation, sensible comments and modular subroutines. These features show that you are thinking about the human reader, not only the computer.

在考试中,使用有意义的变量名、一致的缩进、合理的注释和模块化子程序通常会得分。这些特征表明你不仅在考虑计算机,也在考虑人类读者。

Maintainability also affects the software life cycle: most real programs spend far more time being maintained than being originally written. Therefore, the habits you learn now will save time and reduce errors in larger projects.

可维护性还影响软件生命周期:大多数真实程序在维护上花费的时间远多于最初编写所花的时间。因此,你现在养成的习惯将在更大的项目中节省时间并减少错误。


2. Meaningful Identifiers | 有意义的标识符

Variable, constant, procedure and function names should describe the data they hold or the task they perform. For example, use “totalScore” or “studentName” instead of “x”, “y” or “data1”.

变量、常量、过程和函数的名称应当描述它们保存的数据或执行的任务。例如,使用 “totalScore” 或 “studentName”,而不是 “x”、”y” 或 “data1″。

Cambridge pseudocode requires identifiers to be written clearly, often in camelCase or with underscores. Avoid single-letter names unless they are loop counters such as “i” or “j”, and even then you should comment their purpose if it is not obvious.

剑桥伪代码要求标识符书写清晰,通常使用驼峰命名法或下划线。除非是像 “i” 或 “j” 这样的循环计数器,否则避免使用单字母名称,而且如果目的不明显,你也应注释其用途。

A constant such as “MAX_STUDENTS” is preferable to the number 30 because the name explains both the meaning and the limit. Similarly, a function called “CalculateDiscount” tells you what it does without reading its body.

像 “MAX_STUDENTS” 这样的常量比数字 30 更好,因为名称既解释了含义,也说明了限制。类似地,名为 “CalculateDiscount” 的函数无需阅读其主体就能告诉你它做什么。


3. Comments and Documentation | 注释与文档

Comments explain why a piece of code exists, not what each line does. A good comment might state a precondition, a purpose or a non-obvious decision: “// Search from the end to find the last occurrence”.

注释解释一段代码存在的原因,而不是每一行做了什么。一条好的注释可以说明前置条件、目的或一个不明显的决定:”// 从末尾开始搜索,以找到最后一次出现的位置”。

Do not over-comment trivial lines such as “total = total + 1 // add 1”. The code itself should be readable enough to show what is happening; comments should add value.

不要对像 “total = total + 1 // 加 1” 这样的简单行过度注释。代码本身应可读性足够强,能表明发生了什么;注释应当增加价值。

In pseudocode, it is useful to place a short comment before each procedure or function stating its purpose, parameters and return value. This is sometimes called a function header comment.

在伪代码中,在每个过程或函数之前放置简短注释,说明其用途、参数和返回值,是很有用的。这有时被称为函数头注释。


4. Consistent Indentation and Layout | 一致的缩进与布局

Indentation shows the block structure of IF statements, loops and procedures. In Cambridge pseudocode, the body of a selection or iteration is always indented by a fixed number of spaces, usually four.

缩进显示 IF 语句、循环和过程的块结构。在剑桥伪代码中,选择或迭代的主体总是缩进固定数量的空格,通常为四个。

Consistent layout also includes blank lines between logical sections, alignment of related declarations, and placing constants at the top. These small habits make long programs much easier to scan.

一致的布局还包括逻辑部分之间的空行、相关声明的对齐,以及将常量放在顶部。这些小习惯使长程序更容易浏览。

For example, always write the opening and closing keywords of a loop at the same indentation level, and indent the statements inside. This makes it visually obvious where each block begins and ends.

例如,始终将循环的开始和结束关键字写在相同的缩进级别,并将内部的语句缩进。这使得每个块的开始和结束在视觉上很明显。


5. Modular Design and Subroutines | 模块化设计与子程序

Breaking a program into procedures and functions is one of the most important maintainability techniques. Each subroutine should perform one clear task, such as “VALIDATE_EMAIL()” or “CALCULATE_AVERAGE()”.

将程序拆分为过程和函数是最重要的可维护性技术之一。每个子程序应执行一个明确的任务,例如 “VALIDATE_EMAIL()” 或 “CALCULATE_AVERAGE()”。

Modular design reduces repeated code, isolates errors and allows different parts to be tested independently. In Cambridge pseudocode, you should declare parameters and local variables clearly to avoid unintended side effects.

模块化设计减少了重复代码,隔离了错误,并允许不同部分被独立测试。在剑桥伪代码中,你应该清楚地声明参数和局部变量,以避免意外的副作用。

A well-named subroutine can replace a long block of confusing code. For instance, instead of writing ten lines to check a password, call “ValidatePassword(password)” and hide the details inside the subroutine.

一个命名良好的子程序可以替换一长段令人困惑的代码。例如,不需要写十行来检查密码,而是调用 “ValidatePassword(password)” 并将细节隐藏在子程序内部。


6. Avoiding Magic Numbers and Literals | 避免魔法数字与字面量

A magic number is a hard-coded value whose meaning is not obvious, such as “IF age > 17” without context. Instead, define a constant: “CONSTANT MIN_DRIVING_AGE = 18” and then use “IF age >= MIN_DRIVING_AGE”.

魔法数字是指含义不明显的硬编码值,例如没有上下文的 “IF age > 17″。相反,应定义一个常量:”CONSTANT MIN_DRIVING_AGE = 18″,然后使用 “IF age >= MIN_DRIVING_AGE”。

Using named constants makes the code self-documenting and easier to update. If the law changes, you only need to modify one line, not search through the whole program for the number 18.

使用命名常量使代码具有自文档性且更易于更新。如果法律发生变化,你只需要修改一行,而不是在整个程序中搜索数字 18。

String literals can also be magic values. Instead of repeating “Error: invalid input” many times, store it in a constant such as “ERROR_MESSAGE”. This keeps messages consistent and easy to change.

字符串字面量也可能是魔法值。与其多次重复 “Error: invalid input”,不如将其存储在 “ERROR_MESSAGE” 这样的常量中。这样可以使消息保持一致且易于更改。


7. Defensive Programming and Input Validation | 防御性编程与输入验证

Maintainable programs anticipate invalid or unexpected input. Before processing data, check ranges, types and formats, and use loops to keep asking until the user enters a valid value.

可维护的程序会预见到无效或意外的输入。在处理数据之前,检查范围、类型和格式,并使用循环反复询问,直到用户输入有效值。

For example, a menu-driven program should reject choices outside “1” to “4” with a clear error message. This prevents crashes and makes the program safer to modify later.

例如,一个菜单驱动程序应拒绝 “1” 到 “4” 之外的选择,并给出明确的错误消息。这可以防止崩溃,并使程序在以后修改时更安全。

Defensive programming also means checking for empty input, division by zero, file not found and other common failure points. A maintainable program fails gracefully rather than freezing or producing wrong output.

防御性编程还意味着检查空输入、除零、文件未找到以及其他常见故障点。可维护的程序会优雅地失败,而不是冻结或产生错误输出。


8. Testing and Debugging for Maintenance | 面向维护的测试与调试

You cannot claim code is maintainable if it has not been tested systematically. Use normal, boundary and erroneous data, and record the expected results before running the program.

如果代码没有经过系统测试,你就不能声称它是可维护的。使用正常、边界和错误数据,并在运行程序前记录预期结果。

When debugging, fix the cause rather than the symptom. A maintainable program also includes temporary output statements during development, but these should be removed or commented out in the final version.

调试时,修复原因而不是症状。可维护的程序在开发过程中还会包含临时输出语句,但这些语句在最终版本中应被删除或注释掉。

Writing a short test plan as part of your design makes maintenance easier because you can re-run the same tests after any change to check that nothing has broken. This is called regression testing.

作为设计的一部分编写简短的测试计划会使维护更容易,因为你可以在任何更改后重新运行相同的测试,以检查是否有任何东西被破坏。这被称为回归测试。


9. Refactoring and Code Review | 重构与代码审查

Refactoring means improving the internal structure of existing code without changing its external behaviour. You might rename unclear variables, extract repeated lines into a subroutine, or simplify a complex condition.

重构是指在不改变外部行为的情况下改进现有代码的内部结构。你可以重命名不清楚的变量、将重复的行提取到子程序中,或简化复杂的条件。

Ask a classmate to read your pseudocode. If they cannot understand a section within a few seconds, rewrite it. Peer review is a practical way to evaluate maintainability before submission.

请一位同学阅读你的伪代码。如果他们在几秒钟内无法理解某一部分,就重写它。同行评审是在提交前评估可维护性的一种实用方法。

Refactoring is not an afterthought

Published by TutorHao | 体育 Revision Series | aleveler.com

更多咨询请联系16621398022(同微信)

Comments

屏轩国际教育cambridge primary/secondary checkpoint, cat4, ukiset,ukcat,igcse,alevel,PAT,STEP,MAT, ibdp,ap,ssat,sat,sat2课程辅导,国外大学本科硕士研究生博士课程论文辅导

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from aleveler.com

Subscribe now to keep reading and get access to the full archive.

Continue reading