A-Level Computer Science: Practical Approaches to Writing Maintainable Programs | A-Level计算机:编写可维护程序的实践方法

📚 A-Level Computer Science: Practical Approaches to Writing Maintainable Programs | A-Level计算机:编写可维护程序的实践方法

Maintainable code is code that can be easily read, understood, modified, and debugged by others — or by yourself, months after you wrote it. In A-Level Computer Science, examiners expect you not only to write working code, but also to demonstrate structured, clear, and maintainable practices.

可维护的代码是指能够被他人——或者几周后重新阅读的自己——轻松阅读、理解、修改和调试的代码。在A-Level计算机科学考试中,考官不仅期望你编写能运行的代码,还期望你展示结构化、清晰、可维护的编程实践。


1. Understanding Maintainability | 理解可维护性

Software maintenance often consumes more than 70% of a system’s lifetime cost. Maintainability is the degree to which a program can be updated with minimal effort, minimal risk, and minimal disruption.

软件维护通常占据系统生命周期成本的70%以上。可维护性是指以最小工作量、最小风险、最小干扰来更新程序的程度。

Key indicators of maintainable code include:

可维护代码的关键指标包括:

  • Readability — a human reader can follow the logic quickly.
  • Readability(可读性) —— 人能够快速理解程序逻辑。
  • Modifiability — changing one behaviour does not break unrelated parts.
  • Modifiability(可修改性) —— 修改某一行为不会破坏无关部分。
  • Testability — automated tests can target small units easily.
  • Testability(可测试性) —— 自动化测试能够轻松地针对小单元进行。
  • Documentation — comments and external docs explain ‘why’ behind decisions.
  • Documentation(文档) —— 注释和外部文档解释决策背后的”为什么”。

2. Modular Design | 模块化设计

Modularity means breaking a large problem into smaller, independent sub-problems, each implemented as a function, procedure, or class. Each module should have a single, clear responsibility.

模块化意味着将大型问题分解为更小的、独立的子问题,每个子问题以函数、过程或类的形式实现。每个模块应只有单一的明确职责。

Example — instead of one giant block of code, separate user input from processing from output:

例如——不要使用一个庞大的代码块,而是将用户输入、处理和输出分开:

validate_input() → calculate_result() → format_output()

Benefits of modular design:

模块化设计的优点:

  • Each module can be tested in isolation.
  • 每个模块可以独立测试。
  • Reuse across projects is easier.
  • 跨项目复用更加容易。
  • Debugging: a fault is localised to a small area.
  • 调试:故障被限制在局部区域。
  • Team development: multiple programmers can work in parallel.
  • 团队开发:多个程序员可以并行工作。

3. Meaningful Naming Conventions | 有意义的命名规范

Names should describe purpose, not type. For instance, student_score is better than x. Choose a consistent style — camelCase or snake_case — and apply it everywhere.

名称应描述用途,而非类型。例如,student_scorex 更好。选择一致的风格——camelCase(小驼峰)或 snake_case(下划线命名)——并始终如一地应用。

Guidelines:

准则:

  • Use verbs for functions: calculateAverage(), findMax().
  • 函数使用动词:calculateAverage()findMax()
  • Use nouns for variables and objects: total_marks, student_list.
  • 变量和对象使用名词:total_marksstudent_list
  • Boolean variables use is, has, can: is_valid, has_completed.
  • 布尔变量使用 ishascanis_validhas_completed
  • Constants are usually UPPER_CASE: MAX_SIZE.
  • 常量通常使用全大写:MAX_SIZE
  • Avoid abbreviations like cnt unless standard.
  • 除非是标准缩写,否则避免使用 cnt 这类缩写。

Poor naming forces readers to trace every line; good naming makes the code almost self-documenting.

糟糕的命名迫使阅读者逐行追踪;良好的命名使代码几乎可以自我解释。


4. Comments and Documentation | 注释与文档

Comments should explain why, not what. The code already shows what it does. A comment such as // increment i adds no value. Instead, describe the intention or a non-obvious constraint.

注释应解释”为什么”,而非”做什么”。代码本身已经展示了它做什么。像 // increment i 这样的注释毫无价值。相反,应描述意图或非显而易见的约束。

Useful comment examples:

有用的注释示例:

  • // Use Haversine formula because Earth is a sphere
  • // 使用Haversine公式,因为地球是球体
  • // O(n log n) — required for real-time response
  • // O(n log n)——满足实时响应要求

For larger programs, add a file header comment: author, date, purpose, and version. Also document module interfaces: parameters, return values, and possible errors.

对于较大的程序,添加文件头注释:作者、日期、用途和版本。同时记录模块接口:参数、返回值和可能的错误。


5. Indentation and Code Layout | 缩进与代码布局

Consistent indentation visually reveals the program’s control structure. In Python, indentation is required; in other languages it is still expected style.

一致的缩进在视觉上揭示了程序的控制结构。在Python中,缩进是必需的;在其他语言中,这也是公认的规范风格。

Use 2 or 4 spaces per level — not tabs mixed with spaces. Also keep lines short (e.g. under 80–100 characters) to avoid horizontal scrolling.

每级缩进使用2或4个空格——不要混用制表符和空格。同时保持单行代码较短(例如80–100字符以内),以避免水平滚动。

Compare these two versions:

比较以下两个版本:

if valid: process() else: reject()

if valid:
  process()
else:
  reject()

The second version makes the branching structure explicit and immediately readable.

第二个版本使分支结构清晰明确、立即可读。


6. Avoid Duplicate Code (DRY) | 避免重复代码(DRY原则)

DRY — Don’t Repeat Yourself. Duplicated code multiplies maintenance effort: a bug fixed in one copy may remain in another. Extract common logic into a function or a constant.

DRY——不要重复自己。重复代码成倍地增加维护工作量:在一个副本中修复的bug可能残留在另一副本中。将公共逻辑提取到函数或常量中。

Example: instead of writing the same discount computation three times, write once:

示例:与其三次编写相同的折扣计算,不如编写一次:

def apply_discount(price, rate):
  return price × (1 − rate)

Then call this function from all three places. If the formula changes, only one edit is required.

然后从这三个地方调用该函数。如果公式改变,只需要修改一处。

DRY also applies to data: use a single constant for fixed values instead of retyping literals everywhere.

DRY原则同样适用于数据:为固定值使用单一常量,而不是到处重新输入字面量。


7. Use Constants for Magic Numbers | 使用常量替代魔法数字

Raw numeric literals embedded in code — such as 0.07 for a tax rate — are called magic numbers. They are hard to understand and easy to mistype.

嵌入在代码中的裸数字字面量——例如税金率的 0.07——被称为魔法数字。它们难以理解且容易打错。

Instead, define named constants:

相反,定义具名常量:

TAX_RATE = 0.07
total = subtotal × (1 + TAX_RATE)

Advantages:

优点:

  • Meaning is communicated by the name.
  • 名称传达了含义。
  • If the tax rate changes, only one line needs editing.
  • 如果税率变化,只需要编辑一行。
  • Typing errors are more likely to be noticed.
  • 打字错误更容易被察觉。

8. Robust Error Handling | 健壮的错误处理

Maintainable programs anticipate errors — invalid input, missing files, network drops — and respond gracefully instead of crashing.

可维护的程序会预见错误——无效输入、文件缺失、网络中断——并以优雅的方式响应,而不是崩溃。

Good practices include:

良好的实践包括:

  • Validate all external inputs before processing.
  • 在处理之前验证所有外部输入。
  • Use exception handling (try-except in Python, try-catch in Java).
  • 使用异常处理(Python中的try-except,Java中的try-catch)。
  • Handle each specific exception type separately, not one generic catch-all.
  • 单独处理每种特定异常类型,而不是一个笼统的捕获所有异常。
  • Provide useful error messages containing the actual cause.
  • 提供包含实际原因的有用错误信息。
  • Clean up resources (close files, network connections) even when errors occur.
  • 即使在发生错误时也要清理资源(关闭文件、网络连接)。

Example — reading user input safely:

示例——安全地读取用户输入:

try:
  n = int(input())
except ValueError:
  print(“Please enter an integer.”)


9. Testing for Maintainability | 面向可维护性的测试

Tests protect maintainability by catching regressions when someone modifies code. A small set of automated unit tests gives confidence that refactoring does not break existing behaviour.

测试通过捕获代码修改时的回归问题来保护可维护性。一小组自动化单元测试能让程序员确信重构不会破坏现有行为。

Key testing strategies:

关键测试策略:

  • Test boundary values: empty input, maximum size, negative numbers, zero.
  • 测试边界值:空输入、最大尺寸、负数、零。
  • Test normal cases and intentionally invalid cases.
  • 测试正常情况和故意无效的情况。
  • Use descriptive test names: test_apply_discount_with_zero_rate().
  • 使用具有描述性的测试名称:test_apply_discount_with_zero_rate()
  • Keep tests independent — each test should not depend on another test running first.
  • 保持测试独立——每个测试不应依赖另一个测试先运行。

Well-tested code is easier to extend because you can verify that new features do not break old ones.

经过良好测试的代码更容易扩展,因为你可以验证新功能不会破坏旧功能。


10. Version Control | 版本控制

Version control systems (e.g. Git) are essential for professional and maintainable software. They track every change, allow you to revert to previous versions, and support collaborative workflows.

版本控制系统(例如Git)对于专业且可维护的软件至关重要。它们记录每一次更改,允许你回退到之前的版本,并支持协作式工作流程。

Essential habits:

必要习惯:

  • Commit regularly with clear messages: fix: correct tax calculation for non-residents.
  • 定期提交并附上清晰的提交信息:fix: correct tax calculation for non-residents
  • Commit one logical change at a time.
  • 一次提交一个逻辑变更。
  • Use branches for new features or experiments.
  • 使用分支进行新功能开发或实验。
  • Write a README that explains how to build, run, and test the project.
  • 编写README,说明如何构建、运行和测试项目。

In an exam context, you will not use Git, but you should be able to explain its role and advantages.

在考试环境中,你不会使用Git,但你应该能够解释其作用与优点。


11. Refactoring and Continuous Improvement | 重构与持续改进

Refactoring is the act of improving code structure without changing its external behaviour. It is a routine part of maintaining healthy code.

重构是在不改变外部行为的前提下改进代码结构的行为。它是在维护健康代码过程中的常规部分。

Common refactoring techniques:

常见重构技巧:

  • Extract method — turn a long block into a named function.
  • 提取方法 —— 将一个长代码块转换为具名函数。
  • Rename variable — choose a clearer name based on today’s understanding.
  • 重命名变量 —— 基于当前的理解选择更清晰的名称。
  • Replace conditional with polymorphism — simplify branching in object-oriented code.
  • 用多态替换条件语句 —— 简化面向对象代码中的分支。
  • Remove dead code — delete unused functions and variables.
  • 删除死代码 —— 移除未使用的函数和变量。

Rules of thumb: refactor in small steps and run tests after each step. Never refactor and add new features in the same change.

经验法则:小步重构,并在每一步之后运行测试。绝不在同一次变更中既重构又添加新功能。


12. Summary and Exam Points | 总结与考试要点

For CIE A-Level Computer Science, exam questions on maintainability may ask you to evaluate code, suggest improvements, or describe good practice. Use the following concise checklist in your answers:

对于CIE A-Level计算机科学,关于可维护性的考试题目可能会要求你评估代码、提出改进建议或描述良好实践。在答卷中使用以下简洁清单:

Aspect | 方面 Good Practice | 良好实践
Structure | 结构 Modular functions, each with one purpose | 模块化函数,每个函数单一用途
Naming | 命名 Meaningful, consistent names | 有意义且一致的名称
Comments | 注释 Explain why, not what | 解释为什么而非什么
Layout | 布局 Consistent indentation, short lines | 一致缩进,行文简洁
Duplication | 重复 DRY — extract repeated logic | DRY——提取重复逻辑
Constants | 常量 Replace magic numbers | 替换魔法数字
Errors | 错误 Validate input, use exceptions | 验证输入,使用异常
Testing | 测试 Automated unit tests, boundary cases | 自动化单元测试,边界情况

Remember: maintainability is not an afterthought — it is a continuous discipline that begins with your very first line of code. Marks are awarded for clear structure, suitable naming, relevant comments, and robust logic.

请记住:可维护性不是事后的补充——它是从你编写第一行代码就开始的持续性纪律。清晰的结构、恰当的命名、相关的注释和健壮的逻辑,这些都会为你赢得分数。

Published by TutorHao | A-Level Computer Science 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