Software Development Process软件开发流程
Professional software is not written in one burst of inspiration; it is built through a disciplined life cycle (SDLC) that transforms a vague wish into a working, documented, maintainable product. This guide walks every phase from requirements gathering through design, implementation, testing, documentation, and maintenance, then introduces the collaboration tools, version control (Git) and code review, that make team software development work. Pseudocode and flowcharts appear in the design section; code examples are in Python but the concepts apply to any language.专业软件不是灵感爆发的产物,而是通过严格的生命周期(SDLC,软件开发生命周期)将模糊的需求(requirements,需求)转化为可工作、有文档、可维护产品的结果。本指南逐一讲解需求收集、设计(design,设计)、实现(implementation,实现)、测试(testing,测试)、文档(documentation,文档)和维护(maintenance,维护)各阶段,再介绍版本控制(version control,版本控制,Git)和代码审查等协作工具。设计节包含伪代码和流程图;代码示例用 Python,但概念适用于任何语言。
The Software Development Life Cycle软件开发生命周期
- State the seven SDLC phases in order and match a project activity to its phase.
- Describe the waterfall, agile and spiral models and name one tradeoff of waterfall and of agile.
- Compare a waterfall plan and an agile plan for the same project using week-by-week numbers.
- Explain why a bug fixed after release belongs to maintenance, not testing.
- Match this guide's phase names to the Ontario ICS3U B4.1 list.
- 按顺序说出 SDLC 的七个阶段,并把项目活动对应到相应阶段。
- 描述瀑布(
waterfall)、敏捷(agile)和螺旋(spiral)模型,并说出瀑布和敏捷各一个权衡。 - 用逐周的数字比较同一项目的瀑布计划和敏捷计划。
- 解释为什么发布后修复的错误属于维护而不是测试。
- 把本指南的阶段名称与安大略 ICS3U B4.1 的列表对应起来。
- 1. Problem definition / Requirements1. 问题定义 / 需求: what does the software need to do? Collect user needs, constraints, and success criteria.:软件需要做什么?收集用户需求、约束条件和成功标准。
- 2. Analysis2. 分析: study the requirements in detail; identify inputs, outputs, data flows, and edge cases.:详细研究需求;确定输入、输出、数据流和边缘情况。
- 3. Design3. 设计: produce design artifacts: flowcharts, pseudocode, UML diagrams, data structures, user interface sketches.:产出设计制品:流程图、伪代码、UML 图、数据结构、用户界面草图。
- 4. Implementation (coding)4. 实现(编码): translate the design into working code following coding standards.:按照编码规范将设计转化为可运行的代码。
- 5. Testing5. 测试: verify the code works correctly using a formal test plan (normal, boundary, and error cases).:使用正式测试计划(正常、边界和错误情况)验证代码是否正确运行。
- 6. Documentation / Deployment6. 文档 / 部署: write user and technical documentation; release the software to users.:编写用户文档和技术文档;将软件发布给用户。
- 7. Maintenance7. 维护: fix bugs that appear after release, add new features, and adapt the software as requirements change.:修复发布后出现的错误,添加新功能,并随着需求变化调整软件。
Two phase lists, one process两份阶段列表,同一个过程
Sources word the phases a little differently, so match them by meaning, not by name. This guide puts coding under Implementation and release under Documentation / Deployment. Ontario ICS3U B4.1 lists problem definition, analysis, design, writing code, testing, implementation and maintenance. Its writing code is this guide's Implementation (coding); its implementation, putting the finished program into use, is this guide's Documentation / Deployment. Common error: treating the words as interchangeable. In B4.1, implementation comes after testing.不同资料对阶段的叫法略有差异,所以要按含义而不是按名称来对应。本指南把编码放在“实现”下,把发布放在“文档 / 部署”下。安大略 ICS3U B4.1 列出的是问题定义、分析、设计、编写代码、测试、实现和维护。它的编写代码对应本指南的“实现(编码)”;它的实现(把完成的程序投入使用)对应本指南的“文档 / 部署”。常见错误:把这些词当作可以互换。在 B4.1 中,实现排在测试之后。
Worked Example 1: Mapping a homework tracker through the SDLC例题 1:作业追踪应用的 SDLC 阶段分析
Problem: a student team is tasked with building a homework-tracker app. Walk each SDLC phase for this project.问题:一个学生团队负责构建一个作业追踪应用。逐一分析该项目的每个 SDLC 阶段。
Requirements.需求。 Users (students) need to add tasks with due dates, mark tasks complete, and sort by urgency. Constraint: must work on mobile.用户(学生)需要添加带截止日期的任务、标记任务为已完成并按紧迫性排序。约束:必须在手机上运行。
Analysis.分析。 Inputs: task name, subject, due date. Outputs: sorted task list. Data: each task stores {name, subject, due_date, done}. Edge case: two tasks on the same due date.输入:任务名称、学科、截止日期。输出:已排序的任务列表。数据:每个任务存储 {name, subject, due_date, done}。边缘情况:两个任务的截止日期相同。
Design.设计。 Produce a flowchart for "add task," pseudocode for "sort by due date," and a simple UML class sketch showing Task attributes and methods.为"添加任务"画流程图,为"按截止日期排序"写伪代码,并画出显示 Task 属性和方法的简单 UML 类草图。
Implementation.实现。 Write Python/JavaScript code following the design. Apply coding standards: meaningful names, inline comments, no magic numbers.按照设计编写 Python/JavaScript 代码。遵循编码规范:有意义的命名、内联注释、无魔法数字。
Testing.测试。 Test plan: normal case (add 3 tasks, verify sort), boundary case (task due today), error case (no tasks in list: display "no tasks").测试计划:正常情况(添加 3 个任务,验证排序),边界情况(今天截止的任务),错误情况(列表中无任务:显示"无任务")。
Documentation/Deployment.文档/部署。 Write a README describing how to install and use the app. Deploy to the school server.编写描述如何安装和使用应用的 README。部署到学校服务器。
Maintenance.维护。 Users report that tasks with the same due date display in the wrong order; fix the sort comparator and increment the version number.用户报告截止日期相同的任务显示顺序不正确;修复排序比较器并更新版本号。
Worked Example 2: Comparing a waterfall plan and an agile plan例题 2:比较瀑布计划与敏捷计划
Problem: the homework-tracker team has 16 weeks and 8 features to build. Plan A (waterfall): Requirements 2 weeks, Design 3, Implementation 6, Testing 3, Release 2. Plan B (agile): eight 2-week sprints, each building, testing and releasing one feature. (a) When do users first get working software in each plan? (b) How many releases happen by the end of week 16? (c) In week 8 users ask for a change to feature 5. Which plan absorbs it more cheaply, and why?问题:作业追踪应用的团队有 16 周时间,要完成 8 个功能。方案 A(瀑布):需求 2 周、设计 3 周、实现 6 周、测试 3 周、发布 2 周。方案 B(敏捷):8 个 2 周的冲刺,每个冲刺构建、测试并发布一个功能。(a) 两种方案中用户分别在何时第一次得到可用软件?(b) 到第 16 周结束共有几次发布?(c) 第 8 周用户要求修改功能 5。哪种方案处理起来代价更低,为什么?
Plan A (waterfall).方案 A(瀑布)。 Phases run one after another: Requirements 2 weeks, Design 3, Implementation 6, Testing 3, Release 2. The code below adds them up to find when users first get working software.各阶段依次进行:需求 2 周、设计 3 周、实现 6 周、测试 3 周、发布 2 周。下面的代码把它们加起来,求出用户第一次拿到可用软件的时间。
phases = {"Requirements": 2, "Design": 3, "Implementation": 6, "Testing": 3, "Release": 2}
week = 0
for name, weeks in phases.items():
week += weeks
print(f"{name:<15} ends week {week}")
print("Waterfall: first working release at week", week)
SPRINT_WEEKS = 2
SPRINTS = 8
releases = [SPRINT_WEEKS * n for n in range(1, SPRINTS + 1)]
print("Agile releases at weeks", releases)
Output:输出:
Requirements ends week 2
Design ends week 5
Implementation ends week 11
Testing ends week 14
Release ends week 16
Waterfall: first working release at week 16
Agile releases at weeks [2, 4, 6, 8, 10, 12, 14, 16]
(a) First working software.(a) 第一次得到可用软件。 Waterfall: week 16, because nothing is released until Testing and Release are finished. Agile: week 2, because sprint 1 already ends with a working (small) version.瀑布:第 16 周,因为测试和发布完成之前什么都不会发布。敏捷:第 2 周,因为第 1 个冲刺结束时就已经有一个可用的(小)版本。
(b) Releases.(b) 发布次数。 Waterfall: 1 release (week 16). Agile: 8 releases (weeks 2, 4, 6, 8, 10, 12, 14, 16).瀑布:1 次发布(第 16 周)。敏捷:8 次发布(第 2、4、6、8、10、12、14、16 周)。
(c) The change request in week 8.(c) 第 8 周的变更请求。 Waterfall: the requirements were fixed in weeks 0 to 2 and the design in weeks 2 to 5, and implementation (weeks 5 to 11) is half done, so the change means editing the requirements document, the design and code already written, then re-planning the tests. Agile: sprints 1 to 4 have finished feature 4, and feature 5 has not been started, so the change is made to the backlog (the list of work still to do) before any code for feature 5 exists.瀑布:需求在第 0 到 2 周定稿,设计在第 2 到 5 周定稿,实现(第 5 到 11 周)已完成一半,所以这个变更意味着要修改需求文档、设计和已写好的代码,再重新规划测试。敏捷:冲刺 1 到 4 已完成功能 4,功能 5 还没开始,所以变更只需在待办列表(backlog,尚未完成的工作清单)中修改,此时功能 5 的代码还不存在。
Why this works.为什么这样可行。 Agile shortens the feedback loop (the time between a decision and a user's reaction to it) from 16 weeks to 2. The price is the tradeoff in the cram box: frequent releases need constant communication with users. A real agile sprint still contains a small requirements, design, code and test cycle, so the phases do not disappear. The numbers are a teaching model, not a measurement of any real team.敏捷把反馈回路(从做出决定到用户作出反应之间的时间)从 16 周缩短到 2 周。代价就是速记框里的权衡:频繁发布需要与用户持续沟通。真实的敏捷冲刺内部仍然包含一个小型的需求、设计、编码和测试循环,所以阶段并没有消失。这些数字只是教学模型,并不是对任何真实团队的测量。
Command words: state the seven phases in order; identify the phase an activity belongs to; compare two models by giving a point for each on the same dimension (for example, when users first see working software, or what a late change costs); justify a choice by tying it to the project. Common errors: calling a bug fix after release "testing" (it is maintenance); saying agile has no planning or documentation (it has both, in smaller pieces); calling one model simply better without naming the project; mixing up this guide's phase list with the Ontario B4.1 wording.
指令词:state(陈述)按顺序写出七个阶段;identify(识别)一项活动属于哪个阶段;compare(比较)两种模型时,要在同一维度上各给一点(例如用户何时第一次看到可用软件,或后期变更的代价);justify(论证)选择时要联系具体项目。常见错误:把发布后的错误修复称为“测试”(它是维护);说敏捷没有计划或文档(两者都有,只是更小);不结合项目就说某一种模型更好;把本指南的阶段列表与安大略 B4.1 的措辞混在一起。
Going deeper: agile vs waterfall vs spiral深入:敏捷与瀑布与螺旋模型
CSTA 3B-AP-17 (verbatim): "Plan and develop programs for broad audiences using a software life cycle process. Processes could include agile, spiral, or waterfall." The three models differ in how rigidly they enforce phase order. Waterfall: each phase finishes completely before the next begins; changes are expensive. Agile: short sprints (commonly one to four weeks; this guide uses two), each delivering a working increment; requirements can change between sprints. Spiral: each revolution of the spiral adds risk analysis before the next round of design/build/test. Ontario ICS4U strand B asks students to manage a student team project and names tools such as a Gantt chart, PERT chart or calendar (B1.4); a team may plan that work with sprints or with a Gantt chart. A useful target is to describe each model and name a tradeoff (waterfall: predictable but inflexible; agile: flexible but requires constant communication).CSTA 3B-AP-17(原文):"使用软件生命周期流程为广大受众规划和开发程序。流程可包括敏捷、螺旋或瀑布。"三种模型的区别在于阶段顺序的严格程度。瀑布:每个阶段完全完成后才开始下一个;变更代价高昂。敏捷:短冲刺(通常一到四周;本指南用两周),每次交付一个可运行的增量;需求可在冲刺之间变化。螺旋:每圈螺旋在下一轮设计/构建/测试之前增加风险分析。安大略 ICS4U B 单元要求学生管理学生团队项目,并列出甘特图、PERT 图或日历等工具(B1.4);团队可以用冲刺或甘特图来规划这项工作。一个有用的目标是能够描述每种模型并指出一个权衡(瀑布:可预测但不灵活;敏捷:灵活但需要持续沟通)。
Name the SDLC phase for each activity: (a) interviewing a teacher about what the app must do; (b) drawing a flowchart for "add task"; (c) fixing a crash that users report in March.说出每项活动所属的 SDLC 阶段:(a) 采访老师了解应用必须做什么;(b) 为“添加任务”画流程图;(c) 修复用户在三月报告的崩溃。
(a) Requirements (problem definition): it gathers what the system must do. (b) Design: a flowchart is a design artifact. (c) Maintenance: the software is already released and the bug appeared in use.
(a) 需求(问题定义):收集系统必须做什么。(b) 设计:流程图是设计制品。(c) 维护:软件已经发布,错误是在使用中出现的。
Give one advantage and one disadvantage of the waterfall model.给出瀑布模型的一个优点和一个缺点。
Advantage: the schedule and cost are predictable when the requirements are stable, and each phase has a clear finish. Disadvantage: a change to the requirements late in the project is expensive, and users see nothing working until near the end.
优点:需求稳定时进度和成本可预测,每个阶段都有明确的终点。缺点:项目后期修改需求代价很高,而且用户要到接近结束时才能看到可运行的东西。
Use the numbers of Worked Example 2, but with 4 sprints of 4 weeks instead of 8 sprints of 2 weeks. When is the first release, and how many releases are there by week 16?使用例题 2 的数据,但改为 4 个 4 周的冲刺,而不是 8 个 2 周的冲刺。第一次发布在何时?到第 16 周共有几次发布?
Each sprint ends at week 4, 8, 12 and 16. The first release is at week 4, and there are 4 releases by week 16 (16 / 4 = 4). Longer sprints mean a longer feedback loop, though still shorter than the waterfall plan's 16 weeks.
各冲刺分别在第 4、8、12、16 周结束。第一次发布在第 4 周,到第 16 周共有 4 次发布(16 / 4 = 4)。冲刺越长,反馈回路越长,但仍然比瀑布方案的 16 周短。
Ontario ICS3U B4.1 lists "writing code" and then "implementation" after testing. Which phases of this guide's list do they match?安大略 ICS3U B4.1 列出“编写代码”,并在测试之后列出“实现”。它们分别对应本指南列表中的哪个阶段?
"Writing code" matches this guide's Implementation (coding). B4.1's "implementation" means putting the finished program into use, which matches this guide's Documentation / Deployment. The two lists describe the same process with different words.
“编写代码”对应本指南的“实现(编码)”。B4.1 的“实现”指把完成的程序投入使用,对应本指南的“文档 / 部署”。两份列表用不同的词描述同一个过程。
Requirements and Planning需求与规划
- Classify a requirement as functional or non-functional and give the reason.
- Rewrite a vague requirement so that it is specific, numbered and testable.
- Write a user story with acceptance criteria in Given/When/Then form.
- Find the project length, the critical path and the slack of each task from a list of durations and dependencies.
- Turn a backlog size and a team velocity into a number of sprints.
- 对需求进行功能性或非功能性分类,并说明理由。
- 把含糊的需求改写成具体、有编号、可测试的需求。
- 用“给定 / 当 / 则”(Given/When/Then)形式写出带验收标准的用户故事。
- 根据任务工期和依赖关系,求出项目总长度、关键路径和每个任务的余量。
- 把待办列表的规模和团队速度换算成冲刺数。
- Functional requirements功能性需求: what the system must do. "The user must be able to log in with a username and password." Expressed as user stories or use cases.:系统必须做什么。"用户必须能够用用户名和密码登录。"用用户故事或用例表达。
- Non-functional requirements非功能性需求: how the system must perform. "The login must complete in under 2 seconds." Covers performance, security, accessibility, and maintainability.:系统必须如何运行。"登录必须在 2 秒内完成。"涵盖性能、安全性、无障碍性和可维护性。
Planning: tasks, dependencies and the critical path规划:任务、依赖和关键路径
A plan splits the project into tasks, each with a duration, and records which tasks must finish before another can start (its dependencies). A task can start when its slowest prerequisite finishes. The critical path is the longest chain of dependent tasks; its total is the shortest possible project length, because those tasks cannot overlap. Slack is how long a task can be delayed without delaying the project; tasks on the critical path have slack 0. A Gantt chart draws each task as a bar on a time axis. Ontario ICS4U B1.4 names a Gantt chart or PERT chart as a project-management tool. In a sprint-based plan the team instead measures its velocity, the story points it finishes per sprint, and divides the remaining backlog by it.计划把项目拆分为任务(task),每个任务有工期,并记录哪些任务必须先完成才能开始另一个任务(即它的依赖,dependency)。一个任务在它最慢的前置任务完成后才能开始。关键路径(critical path)是相互依赖的任务中最长的一条链;它的总和就是项目最短可能的长度,因为这些任务无法重叠。余量(slack)是任务可以延误而不拖延项目的时间;关键路径上的任务余量为 0。甘特图(Gantt chart)把每个任务画成时间轴上的一根条。安大略 ICS4U B1.4 把甘特图或 PERT 图列为项目管理工具。在以冲刺为单位的计划中,团队改为衡量自己的速度(velocity,每个冲刺完成的故事点数),再用它去除剩余的待办列表。
Worked Example 3: Writing requirements for a grade calculator例题 3:为成绩计算器编写需求
Problem: write a numbered requirements list for a program that reads five assignment scores and outputs a letter grade.问题:为一个读取五个作业成绩并输出字母等级的程序编写编号需求列表。
Functional requirements.功能性需求。
FR-1: The program shall accept exactly 5 numeric scores as input.
-- 程序应接受恰好 5 个数字成绩作为输入。
FR-2: The program shall compute the arithmetic mean of the 5 scores.
-- 程序应计算 5 个成绩的算术平均值。
FR-3: The program shall output a letter grade (A/B/C/D/F)
based on the mean (A>=90, B>=80, C>=70, D>=60, F otherwise).
-- 程序应根据平均值输出字母等级(A>=90, B>=80, C>=70, D>=60, 否则 F)。
Non-functional requirements.非功能性需求。
NFR-1: Scores outside [0, 100] shall trigger an error message, not a crash.
-- 范围 [0, 100] 之外的成绩应触发错误消息,而非程序崩溃。
NFR-2: The program shall run in Python 3.8+ with no external libraries.
-- 程序应在 Python 3.8+ 中运行,无需外部库。
Notice that every requirement is numbered (so test cases can reference them: "Test for FR-3, boundary case score=90") and testable.注意每个需求都有编号(以便测试用例可以引用它们:"FR-3 的测试,边界情况 score=90")且可测试。
Worked Example 4: Critical path and sprints for the homework tracker例题 4:作业追踪应用的关键路径与冲刺
Problem: the team splits the homework tracker into the ten tasks A to J below (durations in days; the last column lists the tasks that must finish first). (a) How long is the project, and which tasks form the critical path? (b) How much slack does each other task have? (c) Separately, the backlog holds 55 story points and the team's recent velocity is 16 points per sprint. How many sprints are needed?问题:团队把作业追踪应用拆成下表中的 A 到 J 共十个任务(工期以天计;最后一列是必须先完成的任务)。(a) 项目有多长,哪些任务构成关键路径?(b) 其他任务各有多少余量?(c) 另外,待办列表共有 55 个故事点,团队最近的速度为每个冲刺 16 点。需要几个冲刺?
| Task任务 | Activity活动 | Days天数 | Needs first须先完成 |
|---|---|---|---|
| A | Write requirements编写需求 | 3 | - |
| B | Design screens设计界面 | 4 | A |
| C | Design data model设计数据模型 | 2 | A |
| D | Code screens编写界面代码 | 6 | B |
| E | Code storage编写存储代码 | 5 | C |
| F | Integrate集成 | 2 | D, E |
| G | Write test plan编写测试计划 | 3 | C |
| H | Run tests运行测试 | 3 | F, G |
| I | Write user guide编写用户指南 | 2 | F |
| J | Release发布 | 1 | H, I |
The code does a forward pass (earliest start and finish: a task starts when its slowest prerequisite finishes) and then a backward pass (the latest each task may finish without delaying the project).代码先做前向推算(最早开始和结束:任务在最慢的前置任务结束后才开始),再做后向推算(每个任务在不拖延项目的前提下最晚可以何时结束)。
# task: (duration in days, tasks that must finish first)
tasks = {
"A": (3, []), # write requirements
"B": (4, ["A"]), # design screens
"C": (2, ["A"]), # design data model
"D": (6, ["B"]), # code screens
"E": (5, ["C"]), # code storage
"F": (2, ["D", "E"]), # integrate
"G": (3, ["C"]), # write test plan
"H": (3, ["F", "G"]), # run tests
"I": (2, ["F"]), # write user guide
"J": (1, ["H", "I"]), # release
}
# forward pass: a task starts when its slowest prerequisite finishes
start, finish = {}, {}
for name, (days, needs) in tasks.items(): # every prerequisite is listed first
start[name] = max((finish[n] for n in needs), default=0)
finish[name] = start[name] + days
project_days = max(finish.values())
print("Project length:", project_days, "days")
# backward pass: the latest each task may finish without delaying the project
latest_finish = {name: project_days for name in tasks}
for name in reversed(list(tasks)):
days, needs = tasks[name]
for n in needs:
latest_finish[n] = min(latest_finish[n], latest_finish[name] - days)
for name in tasks:
slack = latest_finish[name] - finish[name]
note = " <- critical" if slack == 0 else ""
print(f"{name}: day {start[name]:>2} to {finish[name]:>2}, slack {slack}{note}")
Output:输出:
Project length: 19 days
A: day 0 to 3, slack 0 <- critical
B: day 3 to 7, slack 0 <- critical
C: day 3 to 5, slack 3
D: day 7 to 13, slack 0 <- critical
E: day 5 to 10, slack 3
F: day 13 to 15, slack 0 <- critical
G: day 5 to 8, slack 7
H: day 15 to 18, slack 0 <- critical
I: day 15 to 17, slack 1
J: day 18 to 19, slack 0 <- critical
(a) Project length.(a) 项目长度。 19 days. The critical path is A, B, D, F, H, J: 3 + 4 + 6 + 2 + 3 + 1 = 19.19 天。关键路径是 A、B、D、F、H、J:3 + 4 + 6 + 2 + 3 + 1 = 19。
(b) Slack.(b) 余量。 C and E can each slip 3 days, I 1 day and G 7 days without delaying the release. A one-day delay to any critical task (for example D) delays the release by one day. Task G is not on the critical path even though the test plan is needed: it finishes on day 8 and is not needed until day 15.C 和 E 各可延误 3 天,I 可延误 1 天,G 可延误 7 天,都不会拖延发布。任何关键任务(例如 D)延误一天,发布就延后一天。任务 G 虽然测试计划必不可少,却不在关键路径上:它在第 8 天完成,到第 15 天才会被用到。
Now the sprint view of the same project. The backlog holds 7 stories worth 5, 3, 8, 13, 5, 8 and 13 story points, and the team finished 16, 18 and 14 points in its last three sprints.再看同一项目的冲刺视角。待办列表有 7 个故事,分别为 5、3、8、13、5、8、13 个故事点,团队最近三个冲刺分别完成了 16、18、14 点。
import math
backlog = [5, 3, 8, 13, 5, 8, 13] # story points still to do
last_three_sprints = [16, 18, 14] # points finished in each recent sprint
velocity = sum(last_three_sprints) / len(last_three_sprints)
total = sum(backlog)
sprints_needed = math.ceil(total / velocity)
print("Backlog:", total, "points")
print("Velocity:", velocity, "points per sprint")
print("Sprints needed:", sprints_needed)
Output:输出:
Backlog: 55 points
Velocity: 16.0 points per sprint
Sprints needed: 4
(c) Sprints.(c) 冲刺数。 55 / 16 = 3.4375, and a sprint cannot be partly run, so round up to 4 sprints.55 / 16 = 3.4375,而冲刺不能只做一部分,所以向上取整为 4 个冲刺。
Why this works.为什么这样可行。 The project cannot finish before its longest dependent chain does, so only the critical path sets the length; the other tasks only need to fit inside their slack. Velocity is an estimate from past sprints, so the answer is a forecast to revisit after every sprint, not a promise.项目不可能早于它最长的依赖链完成,所以只有关键路径决定总长度;其他任务只需要在各自的余量内完成。速度是根据过去冲刺得出的估计,所以这个结果是需要在每个冲刺后重新审视的预测,而不是承诺。
Command words: classify a requirement and give the reason (what the system does, or how well it does it); rewrite or improve a vague requirement until a test could pass or fail it; calculate the project length by adding the tasks on the longest chain. Common errors: calling "loads in under 2 seconds" functional; accepting words like fast or user-friendly as requirements; adding every duration instead of the longest chain; starting a task with two prerequisites when the first one finishes instead of the later one; forgetting to round sprints up.
指令词:classify(分类)一个需求并给出理由(系统做什么,还是做得多好);rewrite(改写)或 improve(改进)含糊的需求,直到有一个测试可以判定通过或失败;calculate(计算)项目长度时把最长链上的任务相加。常见错误:把“在 2 秒内加载”当作功能性需求;接受“快”“用户友好”这类词作为需求;把所有工期都加起来而不是只加最长链;有两个前置任务的任务在第一个完成时就开始,而不是等较晚的那个;忘记把冲刺数向上取整。
Going deeper: user stories and acceptance criteria (Agile)深入:用户故事和验收标准(敏捷)
In Agile development, requirements are often written as user stories in the format: "As a [user role], I want [action] so that [benefit]." Example: "As a student, I want to mark a task complete so that I can track my progress." Each story has acceptance criteria, the conditions that must be true for the story to be done: "Given a list of 3 tasks, when I click 'Mark complete' on task 2, then task 2 appears with a strikethrough and moves to the bottom of the list." This Given/When/Then format (also called Gherkin) is used in professional test automation. CSTA 3A-AP-19 says: "Systematically design and develop programs for broad audiences by incorporating feedback from users." User stories are one structured way to record what users need and to check it with them.在敏捷开发中,需求通常以用户故事的格式编写:"作为 [用户角色],我想要 [操作],以便 [获益]。"示例:"作为一名学生,我想要标记任务为已完成,以便我可以追踪进度。"每个故事都有验收标准,故事完成所必须满足的条件:"给定一个包含 3 个任务的列表,当我点击任务 2 的'标记为完成'时,任务 2 应显示删除线并移至列表底部。"这种给定/当/则格式(也称 Gherkin)在专业测试自动化中使用。CSTA 3A-AP-19 指出:"通过纳入用户反馈,系统地为广大受众设计和开发程序。"用户故事是记录用户需求并与用户核对的一种结构化方式。
Classify each requirement and say why: (a) "A teacher can export grades to a spreadsheet." (b) "The export must finish within 5 seconds for 500 students."对每条需求分类并说明理由:(a) “老师可以把成绩导出到电子表格。”(b) “对 500 名学生,导出必须在 5 秒内完成。”
(a) Functional: it states something the system must do (export). (b) Non-functional: it states how well the system must perform (a time limit), and it is testable because 5 seconds can be measured.
(a) 功能性:它规定系统必须做的事(导出)。(b) 非功能性:它规定系统必须达到的性能(时间限制),并且可测试,因为 5 秒可以测量。
Rewrite "The app must be easy to use" as a testable requirement.把“应用必须易用”改写成可测试的需求。
One possible answer: "NFR-3: A first-time user shall add a task in 3 taps or fewer, without instructions." It is numbered, specific and measurable, so a test can count the taps. Other measurable choices are fine.
一个可能的答案:“NFR-3:首次使用的用户应能在不看说明的情况下,用不超过 3 次点击添加一个任务。”它有编号、具体、可量化,所以测试可以数点击次数。其他可量化的写法也可以。
Write a user story with Given/When/Then acceptance criteria for deleting a task.为删除任务写一个带“给定 / 当 / 则”验收标准的用户故事。
Story: "As a student, I want to delete a task so that my list shows only work I still need to do." Acceptance criteria: Given a list of 3 tasks, when I delete task 2, then the list shows 2 tasks and task 2 is gone.
故事:“作为一名学生,我想要删除一个任务,以便我的列表只显示我还需要做的工作。”验收标准:给定一个包含 3 个任务的列表,当我删除任务 2,则列表显示 2 个任务,任务 2 已消失。
Tasks: P (2 days, no prerequisite), Q (3 days, after P), R (4 days, after P), S (1 day, after Q and R). Find the project length, the critical path and the slack of Q.任务:P(2 天,无前置)、Q(3 天,在 P 之后)、R(4 天,在 P 之后)、S(1 天,在 Q 和 R 之后)。求项目长度、关键路径和 Q 的余量。
P ends on day 2. Q ends on day 5 and R ends on day 6. S starts when the later of the two ends (day 6) and ends on day 7. Project length: 7 days. Critical path: P, R, S (2 + 4 + 1 = 7). Q can finish on day 6 without delaying S, so its slack is 6 - 5 = 1 day.
P 在第 2 天结束。Q 在第 5 天结束,R 在第 6 天结束。S 在两者中较晚的那个结束时(第 6 天)开始,在第 7 天结束。项目长度:7 天。关键路径:P、R、S(2 + 4 + 1 = 7)。Q 可以在第 6 天完成而不拖延 S,所以它的余量是 6 - 5 = 1 天。
A backlog holds 40 story points and the team's velocity is 12 points per sprint. How many sprints are needed?待办列表有 40 个故事点,团队速度为每个冲刺 12 点。需要几个冲刺?
40 / 12 = 3.33, and a partly used sprint still takes a whole sprint, so 4 sprints. Three sprints would finish only 36 points.
40 / 12 = 3.33,而部分使用的冲刺仍然要占用整个冲刺,所以需要 4 个冲刺。三个冲刺只能完成 36 点。
Design (Pseudocode, Flowcharts, UML Intro)设计(伪代码、流程图、UML 入门)
- Choose pseudocode, a flowchart or a UML class diagram for a given design problem and justify the choice.
- Draw a flowchart using the correct symbol for each step and two labelled exits from every decision.
- Translate a UML class box into a Python class, and read the attributes and methods back out of a class.
- Trace a pseudocode design by hand on a test input before any code is written.
- 针对给定的设计问题选择伪代码、流程图或 UML 类图,并说明理由。
- 绘制流程图时每一步使用正确的符号,每个判断都有两个带标签的出口。
- 把 UML 类盒子翻译成 Python 类,并能从类中读出属性和方法。
- 在编写任何代码之前,用测试输入手工追踪伪代码设计。
- Pseudocode伪代码: describe the logic of a single algorithm in structured English. Best for capturing loop/decision logic before coding. Uses keywords:
INPUT,OUTPUT,IF/ELSE,WHILE,FOR,SET x TO.:用结构化英语描述单个算法的逻辑。最适合在编码前捕获循环/判断逻辑。使用关键字:INPUT、OUTPUT、IF/ELSE、WHILE、FOR、SET x TO。 - Flowchart流程图: visual representation of algorithm control flow. Oval = Start/End; Rectangle = Process; Diamond = Decision (two exits: YES/NO); Parallelogram = Input/Output. BC CP11 verbatim: "tools to aid in the development process.":算法控制流的可视化表示。椭圆 = 开始/结束;矩形 = 处理;菱形 = 判断(两个出口:是/否);平行四边形 = 输入/输出。BC CP11 原文:"辅助开发过程的工具。"
- UML Class Diagram (intro)UML 类图(入门) shows the attributes and methods of a class in a box with three sections: class name (top), attributes (middle), methods (bottom). Ontario ICS3U B2.4 lists "UML" as an accepted design tool.在三节盒子中显示类的属性和方法:类名(顶部)、属性(中部)、方法(底部)。安大略 ICS3U B2.4 将"UML"列为公认的设计工具。
Worked Example 5: Design artifacts for a login system例题 5:登录系统的设计制品
Problem: produce three design artifacts for a simple username/password login function.问题:为简单的用户名/密码登录功能产出三种设计制品。
1. Pseudocode.1. 伪代码。
INPUT username, password
IF username == "admin" AND password == "pass123" THEN
OUTPUT "Login successful"
ELSE
OUTPUT "Invalid credentials"
END IF
-- 以上:如果用户名为 "admin" 且密码为 "pass123",输出"登录成功",否则输出"无效凭据"。
2. Flowchart (text description).2. 流程图(文字描述)。
Oval "START" → Parallelogram "Input username, password" → Diamond "username='admin' AND password='pass123'?" → YES: Parallelogram "Output: Login successful" → Oval "END"; NO: Parallelogram "Output: Invalid credentials" → Oval "END".椭圆"开始"→ 平行四边形"输入用户名、密码"→ 菱形"username='admin' 且 password='pass123'?"→ 是:平行四边形"输出:登录成功"→ 椭圆"结束";否:平行四边形"输出:无效凭据"→ 椭圆"结束"。
3. UML Class Diagram (intro level).3. UML 类图(入门级)。
+------------------+
| LoginSystem | <-- class name 类名
+------------------+
| - username: str | <-- attributes (- means private)
| - password: str | 属性(- 表示私有)
+------------------+
| + login(): bool | <-- methods (+ means public)
| + logout(): void | 方法(+ 表示公有)
+------------------+
The UML box shows what data the class stores (attributes) and what actions it can perform (methods). This is the design blueprint; the Python implementation follows from it.UML 盒子显示类存储哪些数据(属性)以及可以执行哪些操作(方法)。这是设计蓝图;Python 实现由此而来。
Worked Example 6: From a UML class box to working code例题 6:从 UML 类盒子到可运行的代码
Problem: the design for a Task class in the homework tracker is the UML box in Step 1. Write the Python class it describes, then call it to check that a task due before today is overdue, a finished task is not, and a task due today is not.问题:作业追踪应用中 Task 类的设计就是步骤 1 中的 UML 盒子。写出它所描述的 Python 类,然后调用它来检验:今天之前截止的任务已逾期,已完成的任务不算逾期,今天截止的任务不算逾期。
Step 1. Read the design.步骤 1. 读懂设计。 The UML box below is the design for one task in the homework tracker. The middle section lists three attributes (the data a Task stores); the bottom section lists two methods (what a Task can do).下面的 UML 盒子是作业追踪应用中一个任务的设计。中间部分列出三个属性(Task 存储的数据);底部列出两个方法(Task 能做的事)。
+---------------------------+
| Task |
+---------------------------+
| + title: str |
| + due_date: date |
| + done: bool |
+---------------------------+
| + mark_done(): None |
| + is_overdue(today): bool |
+---------------------------+
Step 2. Translate it.步骤 2. 翻译成代码。 Each attribute becomes an assignment in __init__; each method becomes a def. A design decision has to be made where the box is silent: here a new task starts with done set to False. The last four lines are calls that test the design.每个属性变成 __init__ 中的一条赋值;每个方法变成一个 def。盒子没有说明的地方需要做出设计决定:这里新任务的 done 初始为 False。最后四行是用来检验设计的调用。
from datetime import date
class Task:
def __init__(self, title, due_date):
self.title = title # attribute: title
self.due_date = due_date # attribute: due_date
self.done = False # attribute: done (a new task is not done)
def mark_done(self): # method: mark_done()
self.done = True
def is_overdue(self, today): # method: is_overdue(today)
return (not self.done) and self.due_date < today
essay = Task("Essay draft", date(2026, 11, 20))
lab = Task("Lab report", date(2026, 11, 25))
today = date(2026, 11, 22)
print(essay.is_overdue(today)) # due before today, not done
print(lab.is_overdue(today)) # due after today
essay.mark_done()
print(essay.is_overdue(today)) # done tasks are never overdue
print(lab.is_overdue(date(2026, 11, 25))) # due today is not overdue
Output:输出:
True
False
False
False
Step 3. Check each line against the design.步骤 3. 对照设计检查每一行。 Line 1: the essay is due on 20 November, today is 22 November and it is not done, so it is overdue (True). Line 2: the lab report is due on 25 November, after today, so False. Line 3: after mark_done() a task is never overdue. Line 4: a task due today is not overdue, because due_date < today is false when the dates are equal. This is the "task due today" boundary case from Worked Example 1.第 1 行:作文 11 月 20 日截止,今天是 11 月 22 日且未完成,所以已逾期(True)。第 2 行:实验报告 11 月 25 日截止,在今天之后,所以是 False。第 3 行:调用 mark_done() 之后任务永远不会逾期。第 4 行:今天截止的任务不算逾期,因为日期相等时 due_date < today 为假。这就是例题 1 中“今天截止的任务”这一边界情况。
Why this works.为什么这样可行。 The UML box fixes the names and responsibilities before any code exists, so a teammate can write the code that calls is_overdue in parallel. The box does not say how the methods work; that is what pseudocode or the code itself is for.UML 盒子在任何代码出现之前就固定了名称和职责,所以队友可以同时编写调用 is_overdue 的代码。盒子没有说明方法如何工作;那是伪代码或代码本身的任务。
Command words: draw or represent an algorithm with the correct symbols; design a class by listing attributes and methods; trace an algorithm by hand with a given input; justify the choice of design tool. Common errors: a diamond with one exit, or two exits that are not labelled yes and no; a rectangle where input or output needs a parallelogram; methods listed in the attribute section of a UML box; pseudocode that is really Python and so cannot be read without knowing the language; skipping the design and starting to code.
指令词:draw(绘制)或 represent(表示)算法时使用正确的符号;design(设计)类时列出属性和方法;trace(追踪)算法时用给定输入手工推演;justify(论证)设计工具的选择。常见错误:菱形只有一个出口,或两个出口没有标明是和否;输入输出该用平行四边形却用了矩形;把方法列在 UML 盒子的属性部分;伪代码其实是 Python,不懂这门语言就读不懂;跳过设计直接编码。
Which flowchart symbol is used for (a) "Output: Login successful" and (b) "Is the score at least 90?"下列内容使用哪种流程图符号:(a) “输出:登录成功”;(b) “分数是否至少为 90?”
(a) A parallelogram (input or output). (b) A diamond (decision), with two exits labelled Yes and No.
(a) 平行四边形(输入或输出)。(b) 菱形(判断),带有两个分别标为“是”和“否”的出口。
In the UML box for Task, where do due_date and mark_done() go, and why?在 Task 的 UML 盒子中,due_date 和 mark_done() 分别放在哪一部分,为什么?
due_date is data the object stores, so it goes in the middle (attributes) section. mark_done() is an action the object performs, so it goes in the bottom (methods) section.
due_date 是对象存储的数据,所以放在中间(属性)部分。mark_done() 是对象执行的操作,所以放在底部(方法)部分。
Trace this pseudocode by hand with the inputs 80, 90, 70, -1, and then with the single input -1. SET total TO 0; SET count TO 0; INPUT value; WHILE value != -1: SET total TO total + value; SET count TO count + 1; INPUT value; END WHILE; IF count == 0 THEN OUTPUT "No scores entered" ELSE OUTPUT total / count用输入 80、90、70、-1 手工追踪下面的伪代码,再用只有一个输入 -1 的情况追踪一次。SET total TO 0; SET count TO 0; INPUT value; WHILE value != -1: SET total TO total + value; SET count TO count + 1; INPUT value; END WHILE; IF count == 0 THEN OUTPUT "No scores entered" ELSE OUTPUT total / count
First run: total becomes 80, 170, 240 and count becomes 1, 2, 3; the loop stops at -1; the output is 240 / 3 = 80.0. Second run: the loop body never runs, count is 0, and the program outputs No scores entered instead of dividing by zero. The -1 is a sentinel value that ends the input and is not a score.
第一次:total 依次变为 80、170、240,count 依次变为 1、2、3;遇到 -1 时循环停止;输出 240 / 3 = 80.0。第二次:循环体一次也没执行,count 为 0,程序输出 No scores entered,而不是除以零。-1 是结束输入的哨兵值(sentinel),不是分数。
Why should a design artifact exist before the code is written?为什么在编写代码之前就应该有设计制品?
A design is cheap to change: redrawing a flowchart box takes seconds, while rewriting finished code takes much longer. It also lets a team agree on names, decisions and responsibilities before they work in parallel, and it gives the test plan something to be checked against.
设计的修改成本很低:重画流程图中的一个框只需几秒,而重写已完成的代码要花长得多的时间。设计还让团队在并行工作之前就名称、决定和职责达成一致,并为测试计划提供可对照的依据。
Implementation and Coding Standards实现与编码规范
- Identify violations of meaningful names, named constants, useful comments and consistent indentation in a code snippet.
- Refactor code to use named constants and a lookup table without changing what it does.
- Write a comment that explains why, not what.
- Check that a refactor kept the behaviour by running the old and new versions on the same inputs.
- Describe what a code review looks for.
- 在代码片段中识别违反有意义命名、命名常量、有用注释和一致缩进的地方。
- 在不改变功能的前提下,重构代码以使用命名常量和查找表。
- 写出解释“为什么”而不是“是什么”的注释。
- 用相同输入运行新旧两个版本,检查重构是否保持了行为。
- 描述代码审查要检查什么。
- Meaningful names有意义的命名: variable and function names should say what they store/do.
student_countis good;xis bad (unless it is a local loop counter).:变量和函数名应说明其存储/操作的内容。student_count是好的;x是不好的(除非是局部循环计数器)。 - Inline comments内联注释: explain the why, not the what.
# decrement to convert from 1-indexed to 0-indexedis useful;# add 1is useless. BC CP11 verbatim: "inline commenting to document source code.":解释为什么,而非是什么。# 减去 1 以从 1 索引转换为 0 索引是有用的;# 加 1是无用的。BC CP11 原文:"内联注释记录源代码。" - No magic numbers无魔法数字: replace hard-coded literals with named constants. Instead of
if score >= 90scattered everywhere, useA_THRESHOLD = 90once at the top.:用命名常量替换硬编码的字面量。不要在各处写if score >= 90,而是在顶部一次性定义A_THRESHOLD = 90。 - Consistent indentation and style一致的缩进和风格: use 4 spaces per indent level (Python PEP 8), consistent brace style, and a style guide shared by the team.:每个缩进级别使用 4 个空格(Python PEP 8),一致的花括号风格,以及团队共享的风格指南。
Worked Example 7: Refactoring bad code to meet coding standards例题 7:将糟糕代码重构为符合编码规范的代码
Problem: the following Python code works but violates coding standards. Identify the violations and rewrite it.问题:以下 Python 代码可以运行,但违反了编码规范。识别违规之处并重写。
Original (bad) code.原始(糟糕的)代码。
x = float(input("enter: "))
y = (x*9/5)+32
if y>212:
print("boiling") # hot
Violations identified.识别的违规之处。
- Poor names:
x,y. Magic number:212. Useless comment:# hotjust repeats what the print says. Inconsistent indentation (2 spaces, not 4).命名不佳:x、y。魔法数字:212。无用注释:# hot只是重复了 print 的内容。缩进不一致(2 个空格,而非 4 个)。
Refactored (good) code.重构后(好的)代码。
BOILING_POINT_F = 212 # water boils at 212°F at sea level
# 水在海平面 212°F 沸腾
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9 / 5) + 32
# Check if temperature exceeds boiling point (relevant for lab safety)
# 检查温度是否超过沸点(与实验室安全相关)
if fahrenheit > BOILING_POINT_F:
print("Warning: above boiling point")
The refactored version has meaningful names, a named constant, a useful comment explaining the why, and consistent 4-space indentation. The logic is identical: only the readability changed.重构后的版本具有有意义的名称、命名常量、解释为什么的有用注释以及一致的 4 个空格缩进。逻辑完全相同:只有可读性发生了变化。
Worked Example 8: Refactoring shipping-cost code and proving it still works例题 8:重构运费代码并证明它仍然正确
Problem: the function f(w, z) below works but breaks the coding standards. Identify the violations, refactor it, and show that the refactored version gives the same results.问题:下面的函数 f(w, z) 能运行但违反了编码规范。识别违规之处,重构它,并证明重构后的版本给出相同的结果。
Violations.违规之处。 Names: f, w and z say nothing about shipping, weight or zone. Magic numbers: 5, 2, 8, 3, 12, 4 and -1 are unexplained. Structure: the three branches repeat the same shape, so a fourth zone means copying a branch. There is no docstring, so the units (dollars, kilograms) are not written anywhere.命名:f、w、z 完全看不出运费、重量或区域。魔法数字:5、2、8、3、12、4 和 -1 都没有解释。结构:三个分支形状重复,增加第四个区域就要复制一个分支。没有文档字符串,单位(美元、千克)没有写在任何地方。
Refactor, then check.重构,然后检查。 The new version keeps the rates in one table, names every number, and gets a docstring. A refactor must not change behaviour, so the last lines run the old and the new function on 16 inputs (four weights, four zones, one of them invalid) and count how many outputs agree.新版本把费率放在一张表里,给每个数字命名,并加上文档字符串。重构不能改变行为,所以最后几行用 16 组输入(四种重量、四个区域,其中一个区域无效)同时运行旧函数和新函数,统计有多少输出一致。
# Before: it works, but the names and numbers explain nothing
def f(w, z):
if z == 1:
return 5 + w * 2
elif z == 2:
return 8 + w * 3
elif z == 3:
return 12 + w * 4
else:
return -1
# After: named constants, one lookup table, a docstring
ZONE_RATES = { # zone: (base fee in dollars, dollars per kilogram)
1: (5, 2),
2: (8, 3),
3: (12, 4),
}
INVALID_ZONE = -1
def shipping_cost(weight_kg, zone):
"""Return the shipping cost in dollars, or INVALID_ZONE if the zone is unknown."""
if zone not in ZONE_RATES:
return INVALID_ZONE
base_fee, per_kg = ZONE_RATES[zone]
return base_fee + weight_kg * per_kg
# Behaviour check: run old and new on the same inputs
matches = 0
checked = 0
for weight in (0, 1, 2.5, 10):
for zone in (1, 2, 3, 4):
checked += 1
if f(weight, zone) == shipping_cost(weight, zone):
matches += 1
print(matches, "of", checked, "outputs match")
print(shipping_cost(2.5, 2))
Output:输出:
16 of 16 outputs match
15.5
Reading the result.解读结果。 All 16 outputs match, so the structure changed and the behaviour did not. The last line is a spot check by hand: zone 2 costs 8 + 2.5 × 3 = 15.5 dollars. A rate change is now one edit in ZONE_RATES, and adding a zone is one new line.16 个输出全部一致,所以结构变了而行为没变。最后一行是手工抽查:区域 2 的运费是 8 + 2.5 × 3 = 15.5 美元。现在改费率只需修改 ZONE_RATES 一处,增加区域只需新增一行。
Why this works.为什么这样可行。 Refactoring means improving the structure without changing the behaviour, and the comparison loop is what proves the second half of that sentence. One weakness was kept on purpose: returning -1 for an unknown zone invites a caller to add -1 dollars to a total. Raising a ValueError would be safer, but it changes behaviour, so it belongs in a separate, recorded change.重构的意思是在不改变行为的前提下改进结构,而比较循环正是证明后半句话的依据。有一个缺点被刻意保留:对未知区域返回 -1,可能让调用者把 -1 美元加进总额。抛出 ValueError 会更安全,但这会改变行为,所以应该作为另一次有记录的变更来做。
Command words: identify each violation by name (poor name, magic number, comment that restates the code, inconsistent indentation); rewrite the code so that behaviour is unchanged; explain why a comment helps the next reader. Common errors: a comment that repeats the code (# add 1); turning every number into a constant, including the 0 and 1 of an ordinary loop; renaming and restructuring without running anything to compare; names such as list1 or data2; mixing tabs and spaces in Python.
指令词:identify(识别)每一处违规,并说出名称(命名不佳、魔法数字、重复代码内容的注释、缩进不一致);rewrite(重写)代码且行为不变;explain(解释)注释为什么有助于下一位读者。常见错误:重复代码内容的注释(# add 1);把每个数字都变成常量,包括普通循环里的 0 和 1;重命名和重构之后不运行任何东西做比较;list1、data2 这类名字;在 Python 中混用制表符和空格。
90 in if score >= 90 is a magic number: it should be A_THRESHOLD = 90 at the top of the file. Option B already does this correctly (it is a named constant). Options A and C use variables/range() appropriately.魔法数字是上下文中含义不明显的硬编码字面量。if score >= 90 中的 90 是魔法数字:应该在文件顶部定义 A_THRESHOLD = 90。选项 B 已经正确地这样做了(它是命名常量)。选项 A 和 C 适当地使用了变量/range()。90 for a grade threshold is a magic number: its meaning requires context. Replacing it with A_THRESHOLD = 90 (option B style) is the fix.魔法数字是无法解释的硬编码字面量。成绩阈值的 90 是魔法数字:其含义需要上下文。用 A_THRESHOLD = 90(选项 B 风格)替换它是修复方法。Going deeper: code review as a quality gate深入:代码审查作为质量门
CSTA 3B-AP-23 (verbatim): "Evaluate key qualities of a program through a process such as a code review." A code review is a structured process in which a colleague reads your code before it is merged into the main codebase. Reviewers check: do variable names explain intent? Are all edge cases handled? Is there dead code? Are comments accurate? In professional teams this is often enforced through a pull-request workflow in Git, which many teams set up so that code cannot merge until at least one reviewer approves it. Ontario ICS4U B1.7 (shared resources and version control) and BC CP12 ("Collaboration tools for programming") cover the tools that make this practice possible. For a solo school project, a self-review checklist (naming, comments, constants, edge cases) achieves the same quality improvement.CSTA 3B-AP-23(原文):"通过代码审查等过程评估程序的关键质量。"代码审查是一个结构化过程,同事在代码合并到主代码库之前阅读你的代码。审查者检查:变量名是否解释了意图?是否处理了所有边缘情况?是否有死代码?注释是否准确?在专业团队中,这通常通过 Git 的拉取请求工作流来落实,许多团队会设置为在至少一个审查者批准之前代码无法合并。安大略 ICS4U B1.7(共享资源与版本控制)和 BC CP12"编程协作工具"涵盖了使这种做法成为可能的工具。对于单独的学校项目,自我审查清单(命名、注释、常量、边缘情况)可实现相同的质量改进。
Which literal is a magic number: tax = price * 0.13, count = 0, or for i in range(len(names))? Show the fix.哪个字面量是魔法数字:tax = price * 0.13、count = 0,还是 for i in range(len(names))?给出修改方法。
The 0.13 is a magic number, because its meaning (a sales-tax rate) is not visible. Fix: define SALES_TAX_RATE = 0.13 once and write tax = price * SALES_TAX_RATE. Starting a counter at 0 and looping over a list need no constants.
0.13 是魔法数字,因为它的含义(销售税率)看不出来。修改:一次性定义 SALES_TAX_RATE = 0.13,再写 tax = price * SALES_TAX_RATE。计数器从 0 开始和遍历列表都不需要常量。
Rewrite the useless comment # loop through list above the line for name in names[1:]: so that it helps.改写 for name in names[1:]: 上面那条无用的注释 # loop through list,使它真正有用。
# skip the header row, which is not a student name. It explains why the slice starts at 1, which the code alone does not show.
# skip the header row, which is not a student name(跳过表头行,它不是学生姓名)。它解释了切片为什么从 1 开始,这一点仅看代码是看不出来的。
After a refactor, shipping_cost(2.5, 2) prints 15 instead of 15.5. What does that tell you, and what do you do?重构之后,shipping_cost(2.5, 2) 打印出 15 而不是 15.5。这说明什么,应该怎么做?
The behaviour changed, so the refactor introduced a bug (for example, the weight was converted to an integer). The comparison check is the evidence. Undo or fix the change until the old and new outputs match again.
行为发生了变化,所以重构引入了错误(例如重量被转换成了整数)。比较检查就是证据。撤销或修正这次改动,直到新旧输出再次一致。
Name two things a reviewer checks in a code review.说出代码审查中审查者要检查的两件事。
Any two of: variable names explain intent; edge cases are handled; no dead (unused) code; comments are accurate; constants replace magic numbers; the code follows the team style.
任意两项:变量名说明意图;处理了边缘情况;没有死代码(未使用的代码);注释准确;常量取代了魔法数字;代码符合团队风格。
Testing and Debugging测试与调试
- Write a test plan with scenario, input, expected output, actual output and pass/fail that covers normal, boundary and error cases.
- Work out the expected output from the specification before running the code.
- Run test cases as code and report which pass and which fail.
- Locate a logic error from the pattern of failing boundary tests.
- Name the error category (syntax, logic or run-time) and the Python error type from a traceback.
- 编写包含场景、输入、预期输出、实际输出和通过/失败的测试计划,覆盖正常、边界和错误情况。
- 在运行代码之前,根据规格求出预期输出。
- 把测试用例当作代码运行,并报告哪些通过、哪些失败。
- 根据失败的边界测试的规律定位逻辑错误。
- 根据回溯(
traceback)说出错误类别(语法、逻辑或运行时)和 Python 错误类型。
- Test scenario测试场景: a short description of what is being tested ("Normal login with correct password").:被测内容的简短描述("使用正确密码正常登录")。
- Input data输入数据: the specific values used (username="admin", password="pass123").:使用的具体值(username="admin",password="pass123")。
- Expected output预期输出: what the program should produce if correct ("Login successful").:正确时程序应产生的内容("登录成功")。
- Actual output + Pass/Fail实际输出 + 通过/失败: what the program actually produced, and whether it matches the expected output.:程序实际产生的内容,以及是否与预期输出匹配。
Reading a traceback: what the error type tells you读懂回溯:错误类型说明什么
When Python stops with a run-time error it prints a traceback. Read it from the bottom: the last line names the error type and gives a short message, and the lines above it show which line of your code was running. A syntax error is found before the program starts. A logic error prints nothing at all, which is why a test with a known expected output is the only way to catch it. Each row below was run to get the line quoted.Python 因运行时错误而停止时,会打印回溯(traceback)。要从下往上读:最后一行给出错误类型和简短信息,上面的几行显示出错时正在运行你代码的哪一行。语法错误在程序开始之前就会被发现。逻辑错误什么都不会打印,所以带有已知预期输出的测试是发现它的唯一办法。下表每一行都实际运行过,引用的是真实输出。
| What was run运行了什么 | Last line of the traceback回溯的最后一行 | Category类别 |
|---|---|---|
scores = []sum(scores) / len(scores) | ZeroDivisionError: division by zero | Run-time运行时 |
compute_grade("85") (compares text with a number)(把文本与数字比较) | TypeError: '<=' not supported between instances of 'int' and 'str' | Run-time运行时 |
scores[2] with two scores,但只有两个分数 | IndexError: list index out of range | Run-time运行时 |
int("abc") | ValueError: invalid literal for int() with base 10: 'abc' | Run-time运行时 |
if score >= 90 with the colon missing,缺少冒号 | SyntaxError (the wording after it varies between Python versions)(后面的措辞因 Python 版本而异) | Syntax: found before any line runs语法:在任何一行运行之前就被发现 |
sum(range(1, 5)) meant to add 1 to 5,本意是求 1 到 5 的和 | no message; it prints 10, not 15没有任何提示;它打印 10 而不是 15 | Logic: range(1, 5) stops before 5逻辑:range(1, 5) 在 5 之前停止 |
Worked Example 9: Test plan for a grade calculator例题 9:成绩计算器的测试计划
Write a 4-row test plan for a program that reads a score [0–100] and outputs a letter grade (A≥90, B≥80, C≥70, D≥60, F otherwise).为一个读取 [0–100] 范围内分数并输出字母等级(A≥90,B≥80,C≥70,D≥60,否则 F)的程序编写 4 行测试计划。
| Scenario场景 | Input输入 | Expected output预期输出 | Type类型 |
|---|---|---|---|
| Normal case: B grade正常情况:B 等级 | 85 | B | Normal正常 |
| Boundary: exact A threshold边界:恰好 A 阈值 | 90 | A | Boundary边界 |
| Boundary: one below A threshold边界:A 阈值下一分 | 89 | B | Boundary边界 |
| Error case: out of range错误情况:超出范围 | 150 | Error: score out of range错误:分数超出范围 | Error错误 |
Note: boundary cases at the exact threshold values (90, 80, 70, 60) are critical; they test whether >= is correctly used instead of >. An off-by-one here is a logic error.注意:恰好在阈值(90、80、70、60)处的边界情况至关重要,它们测试是否正确使用 >= 而非 >。这里的差一错误是逻辑错误。
Worked Example 10: Running a test plan as code and debugging the failures例题 10:把测试计划当作代码运行并调试失败
Problem: write a test plan for compute_grade(score) (A for 90 or more, B for 80 or more, C for 70 or more, D for 60 or more, F below 60, and an error outside 0 to 100). Run it against the version below, say which tests fail, find the cause and fix it.问题:为 compute_grade(score) 编写测试计划(90 分及以上为 A,80 分及以上为 B,70 分及以上为 C,60 分及以上为 D,低于 60 为 F,0 到 100 之外为错误)。对下面的版本运行该计划,指出哪些测试失败,找出原因并修复。
Step 1. Write the test plan from the specification.步骤 1. 根据规格编写测试计划。 The specification is: A for 90 or more, B for 80 or more, C for 70 or more, D for 60 or more, F below 60, and a score outside 0 to 100 is an error. The expected column below was worked out from that sentence, before any code was run. Each threshold is its own boundary, so 90, 80, 70 and 60 each get a row.规格是:90 分及以上为 A,80 分及以上为 B,70 分及以上为 C,60 分及以上为 D,低于 60 为 F,0 到 100 之外的分数是错误。下面的预期列是根据这句话算出来的,当时还没有运行任何代码。每个阈值都是各自的边界,所以 90、80、70、60 各占一行。
Step 2. Run the plan against the code.步骤 2. 对代码运行测试计划。 The function below has a deliberate slip. The loop records the actual output and prints PASS or FAIL for each row.下面的函数有一处故意设置的错误。循环记录实际输出,并为每一行打印 PASS 或 FAIL。
def compute_grade(score):
if not (0 <= score <= 100):
raise ValueError("score out of range")
if score > 90: # bug: every comparison should be >=
return "A"
elif score > 80:
return "B"
elif score > 70:
return "C"
elif score > 60:
return "D"
else:
return "F"
# test plan: (scenario, input, expected output)
test_plan = [
("normal B", 85, "B"),
("boundary A", 90, "A"),
("one below A", 89, "B"),
("boundary B", 80, "B"),
("boundary C", 70, "C"),
("boundary D", 60, "D"),
("lowest F", 0, "F"),
("error: too high", 150, "ValueError"),
]
failures = 0
for scenario, score, expected in test_plan:
try:
actual = compute_grade(score)
except ValueError:
actual = "ValueError"
result = "PASS" if actual == expected else "FAIL"
if result == "FAIL":
failures += 1
print(f"{scenario:<16} input={score:<4} expected={expected:<11} actual={actual:<11} {result}")
print(failures, "of", len(test_plan), "tests failed")
Output:输出:
normal B input=85 expected=B actual=B PASS
boundary A input=90 expected=A actual=B FAIL
one below A input=89 expected=B actual=B PASS
boundary B input=80 expected=B actual=C FAIL
boundary C input=70 expected=C actual=D FAIL
boundary D input=60 expected=D actual=F FAIL
lowest F input=0 expected=F actual=F PASS
error: too high input=150 expected=ValueError actual=ValueError PASS
4 of 8 tests failed
Step 3. Diagnose from the pattern.步骤 3. 从规律诊断。 Four rows fail, and they are exactly the four threshold inputs (90, 80, 70, 60); each gets one grade lower than expected. The normal case (85), the "one below" case (89) and the lowest score (0) pass. No error message appears, so this is a logic error, and the pattern points to the comparison: with > a score equal to the threshold falls through to the next grade.有四行失败,恰好是四个阈值输入(90、80、70、60),每个都比预期低一个等级。正常情况(85)、“低一分”的情况(89)和最低分(0)都通过。没有出现任何错误信息,所以这是逻辑错误,而且规律指向比较运算:用 > 时,等于阈值的分数会落到下一个等级。
Step 4. Fix and run the whole plan again.步骤 4. 修复并重新运行整个计划。 Change each > to >= (four lines). Re-running every test, not only the failing ones, shows that the fix broke nothing else:把每个 > 改成 >=(共四行)。重新运行所有测试,而不仅仅是失败的那些,以确认修复没有破坏其他部分:
normal B input=85 expected=B actual=B PASS
boundary A input=90 expected=A actual=A PASS
one below A input=89 expected=B actual=B PASS
boundary B input=80 expected=B actual=B PASS
boundary C input=70 expected=C actual=C PASS
boundary D input=60 expected=D actual=D PASS
lowest F input=0 expected=F actual=F PASS
error: too high input=150 expected=ValueError actual=ValueError PASS
0 of 8 tests failed
Why this works.为什么这样可行。 The expected values came from the specification, so the test could fail. If they had been copied from the program's own output, every row would have passed even with the bug. Without the rows for 80, 70 and 60, only the 90 row would have caught the slip in the first comparison, and the same slip in the other three would have shipped.预期值来自规格,所以测试才有可能失败。如果它们是从程序自己的输出抄来的,即使有错误每一行也都会通过。如果没有 80、70、60 这几行,只有 90 那一行能发现第一个比较中的错误,其他三处同样的错误就会被带到发布版本中。
Command words: design or write a test plan with every column filled; state the expected output (work it out from the specification, not from the program); identify the error type and say how you know; debug by naming the line and the change. Common errors: filling the expected column by running the code; a plan with only normal cases; testing 90 but not 89, or not the other thresholds; calling a wrong answer without a crash a run-time error (it is a logic error); reading PASS in the table without checking that the expected value was right.
指令词:design(设计)或 write(编写)测试计划,每一列都要填;state(陈述)预期输出(根据规格算出,而不是根据程序);identify(识别)错误类型并说明依据;debug(调试)时要指出哪一行以及怎么改。常见错误:通过运行代码来填预期列;计划只有正常情况;测了 90 却没测 89,或没测其他阈值;把没有崩溃的错误答案称为运行时错误(那是逻辑错误);看到表里的 PASS 就算数,却没检查预期值本身是否正确。
if score >= 89 instead of if score >= 90, which sends 89 to A. This is an off-by-one boundary error. (The related slip if score > 90 goes the other way: it sends 90 itself to B.)程序运行不崩溃(不是语法或运行时错误),但产生错误答案,这是逻辑错误。一个可能的原因是 A 阈值处的边界值或运算符写错,例如写成 if score >= 89 而不是 if score >= 90,这会把 89 分类为 A。这是差一边界错误。(相关的另一种失误 if score > 90 方向相反:它会把 90 本身分类为 B。)Going deeper: automated testing and test-driven development Honors: ICS4U / CSE3120深入:自动化测试与测试驱动开发 荣誉:ICS4U / CSE3120
In professional software development, test plans are executed by automated testing frameworks (Python's unittest, JavaScript's Jest, Java's JUnit). Each test case is a function that calls the code under test with specific inputs and asserts the output matches the expected value. Test-driven development (TDD) inverts the order: write the test first (which fails), then write the minimum code to make it pass, then refactor. CSTA 3B-AP-21 (verbatim): "Develop and use a series of test cases to verify that a program performs according to its design specifications." CSE3120 outcome 3.1 also requires iterative testing throughout implementation. For ICS3U, B4.4 asks for a test plan, so a hand-written test plan table is the core skill; automated testing is the Grade-12/advanced extension.在专业软件开发中,测试计划由自动化测试框架执行(Python 的 unittest、JavaScript 的 Jest、Java 的 JUnit)。每个测试用例是一个函数,用特定输入调用被测代码并断言输出与预期值匹配。测试驱动开发(TDD)颠倒了顺序:先编写测试(失败),然后编写最少的代码使其通过,再重构。CSTA 3B-AP-21(原文):"开发和使用一系列测试用例来验证程序是否按照其设计规格运行。" CSE3120 结果 3.1 也要求在整个实现过程中进行迭代测试。对于 ICS3U,B4.4 要求测试计划,所以手写测试计划表是核心技能;自动化测试是 12 年级/高级扩展。
A function accepts ages 13 to 19 inclusive. List the boundary tests and one error test.一个函数接受 13 到 19 岁(含两端)。列出边界测试和一个错误测试。
Boundary tests: 12 (just below, rejected), 13 (lowest valid), 19 (highest valid), 20 (just above, rejected). One error test: a non-number such as the text "abc", which should be rejected without a crash.
边界测试:12(刚好低于范围,应被拒绝)、13(最小有效值)、19(最大有效值)、20(刚好高于范围,应被拒绝)。一个错误测试:非数字,例如文本 "abc",应当被拒绝而不是导致崩溃。
Classify each: (a) print("Total: " + 85) stops with TypeError; (b) a program meant to print 15 for 1+2+3+4+5 prints 10; (c) while True is typed as whlie True:.对每一项分类:(a) print("Total: " + 85) 因 TypeError 而停止;(b) 本该为 1+2+3+4+5 打印 15 的程序打印了 10;(c) 把 while True 误写成 whlie True:。
(a) Run-time error: the program starts and then stops, and the traceback names TypeError. (b) Logic error: it runs to the end with no message but the answer is wrong (for example range(1, 5) stops before 5). (c) Syntax error: Python cannot parse the line, so nothing runs.
(a) 运行时错误:程序启动后才停止,回溯指出 TypeError。(b) 逻辑错误:程序一直运行到结束,没有任何提示,但答案是错的(例如 range(1, 5) 在 5 之前停止)。(c) 语法错误:Python 无法解析这一行,所以什么都不会运行。
Why must the expected output be worked out before the code is run?为什么必须在运行代码之前算出预期输出?
If the expected value is copied from the program's output, the test passes whatever the program does, so it can never find a bug. The expected value has to come from the specification.
如果预期值是从程序输出抄来的,不管程序怎么运行测试都会通过,所以它永远发现不了错误。预期值必须来自规格。
In Worked Example 10, which tests failed, and what single change fixes them?在例题 10 中,哪些测试失败了?什么样的单一修改能修复它们?
The four boundary tests failed (90, 80, 70 and 60). Changing each > to >= in the four comparisons fixes all of them, and the re-run shows 0 of 8 failing.
四个边界测试失败(90、80、70 和 60)。把四处比较中的每个 > 改成 >= 就能全部修复,重新运行显示 8 个中有 0 个失败。
Documentation and Maintenance文档与维护
- Match a document (inline comment, docstring or API reference, README) to its audience.
- Write a docstring with parameters, return value, the error it raises and runnable examples.
- Classify a change request as corrective, adaptive or perfective maintenance.
- Choose a patch, minor or major version bump for a change under semantic versioning.
- Use the examples in a docstring as a test that catches a regression.
- 把文档(内联注释、文档字符串或 API 参考、README)与其受众对应起来。
- 写出包含参数、返回值、会抛出的错误和可运行示例的文档字符串。
- 把变更请求分类为纠正性、适应性或完善性维护。
- 按语义化版本(
semantic versioning)为一项变更选择补丁、次要或主要版本号升级。 - 把文档字符串中的示例当作测试,用来发现回归(
regression)。
- Inline / code comments内联 / 代码注释: audience: future developers (including your future self). Explains non-obvious code decisions using
#or/* */. BC CP11 verbatim: "inline commenting to document source code." CP12 verbatim: "Standardized source code documentation.":受众:未来的开发人员(包括未来的自己)。使用#或/* */解释非显而易见的代码决策。BC CP11 原文:"内联注释记录源代码。" CP12 原文:"标准化源代码文档。" - Technical documentation技术文档: audience: developers maintaining the system. Includes API reference (what each function does, its parameters, return value), data-structure diagrams, and architecture overview.:受众:维护系统的开发人员。包括 API 参考(每个函数的功能、参数、返回值)、数据结构图和架构概述。
- User documentation用户文档: audience: end users. Explains how to install and use the software. Includes a README, user guide, and error-message explanations. Written in plain language, no code.:受众:最终用户。解释如何安装和使用软件。包括 README、用户指南和错误消息说明。用简明语言编写,无代码。
Worked Example 11: Documenting a grade calculator function例题 11:为成绩计算器函数编写文档
Write a properly documented Python function for computing a letter grade, showing three levels of documentation.编写一个有适当文档的 Python 函数来计算字母等级,展示三个层次的文档。
# grade_calculator.py: Dingrui Scholars Grade Tool, v1.0
# Author: student team | Last updated: 2026-01
# License: MIT
# 成绩计算工具,模块说明:根据百分制分数返回字母等级
def compute_grade(score: float) -> str:
"""
Convert a numeric score (0-100) to a letter grade.
将百分制分数(0-100)转换为字母等级。
Parameters / 参数:
score (float): numeric score, must be in [0, 100]
百分制分数,必须在 [0, 100] 范围内
Returns / 返回:
str: letter grade "A", "B", "C", "D", or "F"
字母等级 "A", "B", "C", "D" 或 "F"
Raises / 异常:
ValueError: if score is outside [0, 100]
如果分数超出 [0, 100] 范围
"""
# Validate input before processing (NFR-1)
# 处理前验证输入(对应非功能性需求 NFR-1)
if not (0 <= score <= 100):
raise ValueError(f"Score {score} out of range [0, 100]")
# Grade thresholds: defined as constants to avoid magic numbers
# 成绩阈值:定义为常量以避免魔法数字
A_THRESHOLD, B_THRESHOLD = 90, 80
C_THRESHOLD, D_THRESHOLD = 70, 60
if score >= A_THRESHOLD:
return "A"
elif score >= B_THRESHOLD:
return "B"
elif score >= C_THRESHOLD:
return "C"
elif score >= D_THRESHOLD:
return "D"
else:
return "F"
The docstring (triple-quoted string) is the standard Python technical documentation format. Tools like Sphinx auto-generate HTML documentation from docstrings. The inline comments explain the why. The module header is the user-facing documentation for anyone reading the file.文档字符串(三引号字符串)是标准的 Python 技术文档格式。Sphinx 等工具从文档字符串自动生成 HTML 文档。内联注释解释为什么。模块头是面向任何阅读文件的人的用户文档。
Worked Example 12: Three maintenance tickets, version numbers and a docstring that tests itself例题 12:三张维护工单、版本号和会自我测试的文档字符串
Problem: version 1.0.0 of compute_grade has been released. Three requests arrive: (1) a student who scored 100 gets an error; (2) the school's new gradebook sends scores as text such as "85"; (3) teachers want A- and A+ grades. For each, name the type of maintenance and the new version number under semantic versioning, and show how examples in the docstring catch ticket 1.问题:compute_grade 的 1.0.0 版本已经发布。收到三个请求:(1) 得 100 分的学生遇到错误;(2) 学校新的成绩册把分数以 "85" 这样的文本发送过来;(3) 老师想要 A- 和 A+ 等级。对每个请求,说出维护类型和按语义化版本得到的新版本号,并展示文档字符串中的示例如何发现工单 1 的错误。
Ticket 1: a score of 100 raises an error.工单 1:100 分会引发错误。 The program stops where it should not, so this is corrective maintenance. The fix is backward compatible (every call that worked before still works), so it is a patch: 1.0.0 becomes 1.0.1. The examples in the docstring would have caught the bug. Run against the buggy version (0 <= score < 100), the tests report:程序在不该停止的地方停止了,所以这是纠正性维护。修复向后兼容(以前能用的调用现在仍然能用),所以是补丁:1.0.0 变为 1.0.1。文档字符串里的示例本来就能发现这个错误。对有错误的版本(0 <= score < 100)运行,测试报告:
import doctest
A_THRESHOLD, B_THRESHOLD, C_THRESHOLD, D_THRESHOLD = 90, 80, 70, 60
def compute_grade(score):
"""Return the letter grade for a score from 0 to 100 (inclusive).
>>> compute_grade(100)
'A'
>>> compute_grade(89)
'B'
>>> compute_grade(101)
Traceback (most recent call last):
...
ValueError: Score 101 out of range [0, 100]
"""
if not (0 <= score < 100): # v1.0.0: the bug is "< 100"
raise ValueError(f"Score {score} out of range [0, 100]")
if score >= A_THRESHOLD:
return "A"
elif score >= B_THRESHOLD:
return "B"
elif score >= C_THRESHOLD:
return "C"
elif score >= D_THRESHOLD:
return "D"
return "F"
print(doctest.testmod())
Output, with the file-name line and the middle of the traceback left out:输出(省略了文件名一行和回溯的中间部分):
Failed example:
compute_grade(100)
Exception raised:
...
ValueError: Score 100 out of range [0, 100]
**********************************************************************
1 item had failures:
1 of 3 in __main__.compute_grade
***Test Failed*** 1 failure.
TestResults(failed=1, attempted=3)
After changing the check to 0 <= score <= 100 and running the same file again:把检查改为 0 <= score <= 100 后再次运行同一个文件:
TestResults(failed=0, attempted=3)
Ticket 2: the new gradebook sends scores as text such as "85".工单 2:新成绩册把分数以 "85" 这样的文本发送过来。 The environment the program runs in has changed and the functionality has not, so this is adaptive maintenance. Accepting text is a new capability and old calls such as compute_grade(85) still work, so it is a minor change: 1.0.1 becomes 1.1.0 (the patch number resets to 0).程序运行的环境变了而功能没变,所以这是适应性维护。接受文本是新增能力,而 compute_grade(85) 这样的旧调用仍然有效,所以是次要变更:1.0.1 变为 1.1.0(补丁号归零)。
Ticket 3: teachers want A- and A+.工单 3:老师想要 A- 和 A+。 Adding a feature is perfective maintenance. But a score of 91 would now return "A-" where it returned "A" before, so code that compares the result with "A" can break. An incompatible change is a major change: 1.1.0 becomes 2.0.0 (minor and patch reset to 0).新增功能是完善性维护。但 91 分现在会返回 "A-",而以前返回 "A",所以拿结果与 "A" 比较的代码可能出错。不兼容的变更是主要变更:1.1.0 变为 2.0.0(次要号和补丁号归零)。
Documentation to update.需要更新的文档。 The docstring (technical documentation) gets the new examples, the README (user documentation) gets the new input formats and grades, and a short changelog records the three version numbers and what changed.文档字符串(技术文档)加入新示例,README(用户文档)加入新的输入格式和等级,一份简短的变更日志记录三个版本号及变更内容。
Why this works.为什么这样可行。 The version number tells users how risky an upgrade is, and the tests inside the documentation make a change safe to ship. Semantic versioning (MAJOR.MINOR.PATCH) is one common convention, not the only one.版本号告诉用户升级的风险有多大,而写在文档里的测试让变更可以放心发布。语义化版本(MAJOR.MINOR.PATCH)是一种常见约定,不是唯一的约定。
Command words: identify the audience of a document (developer, maintainer, end user); classify a change as corrective, adaptive or perfective and give the reason; write a docstring that states parameters, return value and exceptions. Common errors: calling a new feature adaptive (a new feature is perfective; a changed environment is adaptive); calling a bug fix after release "testing"; putting code in user documentation; a docstring that explains how the function works instead of what it promises; leaving out the exception the function raises.
指令词:identify(识别)文档的受众(开发人员、维护人员、最终用户);classify(分类)变更为纠正性、适应性或完善性并给出理由;write(编写)说明参数、返回值和异常的文档字符串。常见错误:把新功能称为适应性(新功能是完善性,环境变化才是适应性);把发布后的错误修复称为“测试”;在用户文档中放代码;文档字符串解释函数如何工作而不是它承诺什么;漏掉函数会抛出的异常。
Which audience is each aimed at: (a) the comment # skip the header row; (b) a README line "Run python grade.py and type your five scores"; (c) an API reference page listing every function and its parameters?下面分别面向哪类受众:(a) 注释 # skip the header row;(b) README 中的一行“运行 python grade.py 并输入你的五个分数”;(c) 列出每个函数及其参数的 API 参考页?
(a) Developers reading the code, including the author later. (b) End users, in plain language. (c) Developers who maintain or build on the system (technical documentation).
(a) 阅读代码的开发人员,包括以后的作者本人。(b) 最终用户,使用简明语言。(c) 维护或基于该系统开发的开发人员(技术文档)。
Classify each change: (a) fix the crash when the input list is empty; (b) make the program run on Python 3.12 after the school server upgrades; (c) add CSV export.对每项变更分类:(a) 修复输入列表为空时的崩溃;(b) 学校服务器升级后让程序在 Python 3.12 上运行;(c) 增加 CSV 导出。
(a) Corrective: a bug is fixed. (b) Adaptive: the environment changed and the behaviour did not. (c) Perfective: a feature is added.
(a) 纠正性:修复了错误。(b) 适应性:环境变了而行为没变。(c) 完善性:增加了功能。
The current version is 2.3.4. Give the next version for: (a) a bug fix; (b) a new feature that keeps all old calls working; (c) removing a function that other programs call.当前版本是 2.3.4。分别给出下一个版本号:(a) 修复错误;(b) 新增功能且所有旧调用仍然有效;(c) 删除其他程序会调用的函数。
(a) 2.3.5 (patch). (b) 2.4.0 (minor; the patch number resets to 0). (c) 3.0.0 (major, because existing callers break; minor and patch reset to 0).
(a) 2.3.5(补丁)。(b) 2.4.0(次要;补丁号归零)。(c) 3.0.0(主要,因为现有调用者会出错;次要号和补丁号归零)。
A function root(n) raises ValueError when n is negative. Write the line of its docstring that documents this.函数 root(n) 在 n 为负数时抛出 ValueError。写出文档字符串中记录这一点的那一行。
Raises: ValueError: if n is negative (any clear wording that names the exception and the condition is acceptable). The caller then knows to handle that case.
Raises: ValueError: if n is negative(任何清楚指出异常及其条件的写法都可以)。这样调用者就知道要处理这种情况。
Collaboration and Version Control (Git Intro)协作与版本控制(Git 入门)
- State what
git init,git add,git commitandgit pusheach do, and which of them change only your own computer. - Explain how branches let two people work at the same time and what a merge conflict is.
- Read a conflict marker block and resolve it.
- Write a commit message that says what changed and why.
- 说出
git init、git add、git commit和git push各自的作用,以及其中哪些只改变你自己的电脑。 - 解释分支如何让两个人同时工作,以及什么是合并冲突(
merge conflict)。 - 读懂冲突标记块并解决冲突。
- 写出说明“改了什么、为什么改”的提交消息。
git init: initialise a new Git repository in the current folder. Creates a hidden.gitdirectory that tracks all future changes.:在当前文件夹中初始化一个新的 Git 仓库。创建一个隐藏的.git目录来追踪所有未来的更改。git add <file>: stage a file for the next commit (mark it as "ready to save").git add .stages all changed files at once.:将文件暂存为下一次提交(标记为"准备保存")。git add .一次暂存所有更改的文件。git commit -m "message": save a snapshot of all staged files with a descriptive message. Each commit is a permanent, retrievable checkpoint.:用描述性消息保存所有暂存文件的快照。每次提交都是一个永久的、可检索的检查点。git push: upload local commits to a remote repository (e.g., GitHub). Enables team members to access your work.:将本地提交上传到远程仓库(如 GitHub)。使团队成员能够访问你的工作。
Worked Example 13: A typical Git workflow for a school project例题 13:学校项目的典型 Git 工作流
A pair of students is building a grade calculator. Trace their Git workflow from start to submission.两名学生正在构建成绩计算器。追踪他们从开始到提交的 Git 工作流。
# Day 1: Student A sets up the repository
# 第 1 天:学生 A 创建仓库
git init -b main grade-calc
cd grade-calc
# 创建 grade_calculator.py 并编写初始函数
git add grade_calculator.py
git commit -m "Add compute_grade() function with A/B/C/D/F thresholds"
# 连接远程仓库(只需做一次)
git remote add origin https://github.com/team/grade-calc
git push origin main
# Day 2: Student B clones and adds tests
# 第 2 天:学生 B 克隆并添加测试
git clone https://github.com/team/grade-calc
# 编写 test_grade_calculator.py 测试文件
git add test_grade_calculator.py
git commit -m "Add test plan: normal, boundary, and error cases for compute_grade()"
git push origin main
# Day 3: Student A fixes a boundary bug found by the tests
# 第 3 天:学生 A 修复测试发现的边界错误
# 将 'score > 90' 修正为 'score >= 90'(差一错误)
git add grade_calculator.py
git commit -m "Fix off-by-one: change > to >= for A threshold (fixes test TC-2)"
git push origin main
Each commit message is specific: it says what changed and why. This makes the project history readable: anyone can understand the change log without opening each file. The commit message "fixes test TC-2" links the code change to the test plan row, closing the requirements → design → implement → test → fix loop.每条提交消息都很具体:它说明了更改了什么以及为什么。这使项目历史可读:任何人都可以在不打开每个文件的情况下理解变更日志。提交消息"fixes test TC-2"将代码更改与测试计划行关联起来,形成需求 → 设计 → 实现 → 测试 → 修复的完整闭环。
Worked Example 14: Two branches, a merge conflict and its resolution例题 14:两个分支、一次合并冲突及其解决
Problem: two students both change the A threshold in grade_calculator.py, each on a different branch. Show what happens when the branches are merged, how to read the conflict, and how to finish the merge.问题:两名学生各在不同的分支上修改 grade_calculator.py 中的 A 阈值。展示合并分支时会发生什么、如何读懂冲突,以及如何完成合并。
Step 1. Two people change the same line on different branches.步骤 1. 两个人在不同分支上修改同一行。 Student B works on the branch fix-threshold; Student A stays on main. git commit -am stages every tracked file that changed and commits in one step. Then A tries to merge B's branch.学生 B 在分支 fix-threshold 上工作;学生 A 留在 main 上。git commit -am 一步完成暂存所有已跟踪的改动文件并提交。随后 A 尝试合并 B 的分支。
git init -b main grade-calc
cd grade-calc
# grade_calculator.py contains one line: A_THRESHOLD = 90
git add grade_calculator.py
git commit -m "Add A threshold"
git switch -c fix-threshold # Student B works on a separate branch
# B edits the line to: A_THRESHOLD = 85
git commit -am "Lower A threshold to 85"
git switch main # Student A is still on main
# A edits the same line to: A_THRESHOLD = 95
git commit -am "Raise A threshold to 95"
git merge fix-threshold
Git's reply:Git 的回应:
Auto-merging grade_calculator.py
CONFLICT (content): Merge conflict in grade_calculator.py
Automatic merge failed; fix conflicts and then commit the result.
Step 2. Read the conflict.步骤 2. 读懂冲突。 Both branches changed the same line, so Git cannot know which value is right and stops the merge. git status --short marks the file UU (both sides modified), and Git writes both versions into the file between three marker lines: the part between <<<<<<< HEAD and ======= is the current branch (main, value 95); the part between ======= and >>>>>>> fix-threshold is the incoming branch (value 85).两个分支修改了同一行,Git 无法知道哪个值正确,于是中止合并。git status --short 把该文件标为 UU(双方都修改过),Git 把两个版本都写进文件,并用三种标记行隔开:<<<<<<< HEAD 与 ======= 之间是当前分支(main,值 95);======= 与 >>>>>>> fix-threshold 之间是传入的分支(值 85)。
git status --short
UU grade_calculator.py
cat grade_calculator.py
<<<<<<< HEAD
A_THRESHOLD = 95
=======
A_THRESHOLD = 85
>>>>>>> fix-threshold
Step 3. Resolve and finish the merge.步骤 3. 解决冲突并完成合并。 The students talk and agree on 90. They edit the file so that one correct line remains and all three marker lines are deleted. Then git add tells Git the conflict is resolved, and git commit records the merge.两位学生商量后一致同意用 90。他们编辑文件,只留下一行正确的内容,并且删除全部三种标记行。然后 git add 告诉 Git 冲突已解决,git commit 记录这次合并。
# edit the file by hand: keep one line, delete all three marker lines
# A_THRESHOLD = 90
git add grade_calculator.py
git commit -m "Merge fix-threshold: settle on 90"
git log --graph --format="%s"
Output of the last command (the history, newest first):最后一条命令的输出(历史记录,最新的在最前):
* Merge fix-threshold: settle on 90
|\
| * Lower A threshold to 85
* | Raise A threshold to 95
|/
* Add A threshold
Why this works.为什么这样可行。 The graph shows two lines of work that split and then join. A conflict appears only when both sides change the same lines; changes to different files, or different lines of one file, merge on their own. The markers are not valid Python, so a file committed with a marker left in it fails with SyntaxError: invalid syntax as soon as it runs. Commit messages such as "Raise A threshold to 95" say what changed and make the history readable; "update" does not. The short hash codes that Git prints after each commit are different on every computer, so they are left out here.这张图显示两条工作线分开后又汇合。只有双方修改同样的行时才会出现冲突;修改不同文件,或同一文件的不同行,会自动合并。标记行不是合法的 Python,所以提交时若留下标记,文件一运行就会报 SyntaxError: invalid syntax。像“Raise A threshold to 95”这样的提交消息说明了改了什么,使历史可读;“update”则不行。Git 在每次提交后打印的短哈希码在每台电脑上都不同,所以这里省略了。
Command words: describe or explain what each command does and where the change lands (your own computer, or the shared remote); outline the order of the commands; resolve a conflict by reading both sides. Common errors: saying commit uploads work (only push does); forgetting git add, so the new file is missing from the commit; vague messages such as "update" or "stuff"; deleting one person's change without reading it; leaving marker lines in the file.
指令词:describe(描述)或 explain(解释)每条命令的作用以及改动落在哪里(你自己的电脑,还是共享的远程仓库);outline(概述)命令的顺序;resolve(解决)冲突时要读懂双方的内容。常见错误:说 commit 会上传工作(只有 push 会);忘记 git add,导致新文件没有进入提交;“update”“stuff”之类含糊的提交消息;不看内容就删掉某个人的修改;把标记行留在文件里。
git commit -m "Add login function" do?git commit -m "Add login function" 做什么?git commit saves a permanent snapshot (checkpoint) of all staged files. The -m flag provides the commit message. Uploading to GitHub requires a separate git push command; marking files ready is git add; creating a repo is git init.git commit 保存所有暂存文件的永久快照(检查点)。-m 标志提供提交消息。上传到 GitHub 需要单独的 git push 命令;标记文件就绪是 git add;创建仓库是 git init。commit saves locally; push uploads to remote.Git 工作流:init → add(暂存)→ commit(快照)→ push(上传)。commit 本地保存;push 上传到远程。Going deeper: branching strategies and pull requests Honors: ICS4U B1.7 / CSTA 3B-AP-20深入:分支策略和拉取请求 荣誉:ICS4U B1.7 / CSTA 3B-AP-20
CSTA 3B-AP-20 (verbatim): "Use version control systems, integrated development environments (IDEs), and collaborative tools and practices (code documentation) in a group software project." In professional teams, the workflow is: (1) create a feature branch from main (git checkout -b feature/login); (2) commit work on the feature branch; (3) open a pull request (PR): a request to merge the feature branch into main; (4) teammates review the PR (checking for bugs, style, test coverage); (5) after approval, the branch is merged and deleted. This workflow helps keep untested code out of the main codebase. Ontario ICS4U B1.7 names "proper version control" for managing a Grade-12 team project; the pull-request workflow is one widely used way to practise it.CSTA 3B-AP-20(原文):"在团队软件项目中使用版本控制系统、集成开发环境(IDE)和协作工具及实践(代码文档)。"在专业团队中,工作流是:(1) 从 main 创建功能分支(git checkout -b feature/login);(2) 在功能分支上提交工作;(3) 开启拉取请求(PR):合并功能分支到 main 的请求;(4) 队友审查 PR(检查错误、风格、测试覆盖率);(5) 批准后,合并并删除分支。这个工作流有助于防止未经测试的代码进入主代码库。安大略 ICS4U B1.7 在 12 年级团队项目中提到"正确的版本控制";拉取请求工作流是实践它的一种常用方式。
Put these in the order a student uses them to save new work and share it: git push, git add, git commit -m "...". What goes wrong if git add is skipped?把下面的命令按学生保存并分享新工作的顺序排列:git push、git add、git commit -m "..."。如果跳过 git add 会出什么问题?
Order: git add, then git commit -m "...", then git push. Without git add, the new or changed file is not staged, so the commit does not contain it and the pushed history lacks the work.
顺序:git add,然后 git commit -m "...",最后 git push。如果没有 git add,新增或修改的文件没有被暂存,提交里就不包含它,推送的历史也就缺少这部分工作。
Which of git add, git commit and git push change something outside your own computer?git add、git commit、git push 中哪些会改变你自己电脑之外的东西?
Only git push. git add and git commit work on your local repository; git push uploads the commits to the remote (for example GitHub).
只有 git push。git add 和 git commit 作用于你的本地仓库;git push 把提交上传到远程仓库(例如 GitHub)。
Why is "update" a poor commit message? Write a better one for changing the A threshold from 90 to 85.为什么“update”是糟糕的提交消息?为把 A 阈值从 90 改成 85 写一条更好的消息。
It says neither what changed nor why, so the history cannot be searched or understood. Better: "Lower A threshold from 90 to 85", with the reason added if it is not obvious.
它既没有说明改了什么,也没有说明为什么,所以无法检索或理解历史。更好的写法:“Lower A threshold from 90 to 85”,如果原因不明显,再补上原因。
What do the lines <<<<<<< HEAD, ======= and >>>>>>> fix-threshold mean, and what must happen to them before the merge is committed?<<<<<<< HEAD、======= 和 >>>>>>> fix-threshold 这几行是什么意思?在提交合并之前必须对它们做什么?
They fence off the two competing versions of the same lines: your current branch above =======, the incoming branch below it. Before committing, decide the final content and delete all three marker lines, then run git add and git commit.
它们把同一行内容的两个互相竞争的版本隔开:======= 上面是你当前的分支,下面是传入的分支。提交之前要确定最终内容并删除全部三种标记行,然后运行 git add 和 git commit。
Two students edit different files on different branches. Will the merge conflict?两名学生在不同分支上编辑不同的文件。合并会冲突吗?
No. Git merges changes to different files automatically. A conflict needs both branches to change the same lines of the same file.
不会。Git 会自动合并对不同文件的修改。冲突要求两个分支修改同一个文件的相同行。
Exam Strategy and Common Pitfalls考试策略与常见陷阱
- Name and sequence all seven phases.命名并排序全部七个阶段。 Ontario ICS3U B4.1 names the phases explicitly. A typical question asks you to identify which SDLC phase a given activity belongs to. Know: Requirements → Analysis → Design → Implementation → Testing → Documentation/Deployment → Maintenance.安大略 ICS3U B4.1 明确命名各阶段。典型的题目会要求你确定某项活动属于哪个 SDLC 阶段。牢记:需求 → 分析 → 设计 → 实现 → 测试 → 文档/部署 → 维护。
- Waterfall vs Agile: one key tradeoff each.瀑布 vs 敏捷:各一个关键权衡。 Waterfall: predictable schedule but expensive to change. Agile: flexible but requires constant communication. CSTA 3B-AP-17 names both; know one advantage and one disadvantage of each.瀑布:进度可预测,但变更代价高昂。敏捷:灵活但需要持续沟通。CSTA 3B-AP-17 命名了两者;各知道一个优点和一个缺点。
- Functional vs non-functional.功能性 vs 非功能性。 Functional = what the system does. Non-functional = how it performs (speed, security, accessibility). Practice questions often give a requirement and ask you to classify it.功能性 = 系统做什么。非功能性 = 如何执行(速度、安全性、无障碍性)。练习题常给出一个需求,要求你对其分类。
- Design artifact match.设计制品匹配。 Pseudocode/flowchart → algorithm logic. UML class diagram → object structure. Know which tool to use for which problem, citing ICS3U B2.4 if you need to justify tool choice.伪代码/流程图 → 算法逻辑。UML 类图 → 对象结构。了解哪种工具用于哪种问题,如果需要证明工具选择,引用 ICS3U B2.4。
- Name the error type precisely.精确命名错误类型。 Syntax: fails to parse. Logic: wrong answer, no crash. Runtime: crash during execution. Use the exact term. BC CP11 uses "logical or semantic" errors; some courses use "semantic" as another word for logic, so follow your teacher's wording.语法:无法解析。逻辑:答案错误,无崩溃。运行时:执行期间崩溃。使用准确的术语。BC CP11 使用"逻辑或语义"错误;有些课程把"语义"当作逻辑错误的另一种说法,所以请遵循你老师的用词。
- Test plan: always write all three case types.测试计划:始终编写全部三种情况类型。 Normal, boundary, error/exception. Ontario B4.4 and AB CSE1110 1.7 both require testing for failure as well as success. A test plan with only normal cases is an incomplete plan.正常、边界、错误/异常。安大略 B4.4 和 AB CSE1110 1.7 都要求对失败和成功情况都进行测试。只有正常情况的测试计划是不完整的计划。
- Three documentation audiences.三类文档受众。 Inline comments → developers. API/technical docs → developer-maintainers. User guide/README → end users. A typical question describes a document and asks which audience it serves.内联注释 → 开发人员。API/技术文档 → 开发维护人员。用户指南/README → 最终用户。典型的题目会描述一份文档,要求说明它服务的受众。
- Four core Git commands in order.四个核心 Git 命令的顺序。
git init→git add→git commit→git push. Know what each command does. ICS4U B1.7 names version control; knowing these four commands gives you concrete specifics to cite.git init→git add→git commit→git push。了解每个命令的作用。ICS4U B1.7 提到版本控制;了解这四个命令为你提供具体、可引用的细节。
Flashcards闪卡
Practice Quiz综合测验
total_enrolled_students is the most descriptive: it tells any developer exactly what it stores without needing a comment. Coding standards require meaningful names. "students" is reasonable but "total" clarifies it is a count, not a list. "x" and "n" are meaningless as variable names for this purpose.total_enrolled_students 是最具描述性的:它准确告诉任何开发人员它存储的内容,无需注释。编码规范要求有意义的命名。"students"合理,但"total"澄清了它是一个计数,而非列表。"x"和"n"作为此目的的变量名毫无意义。git push uploads local commits to the remote repository. git commit saves a snapshot locally; git add stages files; git init creates a new repository. The workflow is: init → add → commit → push.git push 将本地提交上传到远程仓库。git commit 在本地保存快照;git add 暂存文件;git init 创建新仓库。工作流程是:init → add → commit → push。Readiness Checklist准备就绪清单
Tick each item when you can do it cold, without notes, on a first attempt.能在无笔记、首次尝试下完成,再勾选每一项。
- Name all seven SDLC phases in order and give a concrete example of one activity that happens in each phase for a simple school app project. 🇨🇦 ON ICS3U B4.1 / 🇺🇸 CSTA 3B-AP-17按顺序命名全部七个 SDLC 阶段,并为简单学校应用项目举出每个阶段发生的一项活动的具体例子。🇨🇦 ON ICS3U B4.1 / 🇺🇸 CSTA 3B-AP-17
- Write a numbered requirements document for a given problem, including at least two functional requirements and one non-functional requirement, each specific and testable. 🇨🇦 ON ICS3U B4.1 / 🇺🇸 CSTA 3A-AP-19为给定问题编写编号需求文档,包括至少两个功能性需求和一个非功能性需求,每个都具体且可测试。🇨🇦 ON ICS3U B4.1 / 🇺🇸 CSTA 3A-AP-19
- Produce two design artifacts for a given problem: a pseudocode/flowchart for an algorithm AND a UML class diagram showing at least two attributes and one method. 🇨🇦 ON ICS3U B2.4 / BC CP11为给定问题产出两种设计制品:算法的伪代码/流程图以及显示至少两个属性和一个方法的 UML 类图。🇨🇦 ON ICS3U B2.4 / BC CP11
- Identify the four coding standard violations in a given code snippet (poor names, magic numbers, useless comments, inconsistent indentation) and rewrite it to standards. 🇨🇦 BC CP11 "inline commenting" / ON ICS3U B2.4识别给定代码片段中的四个编码规范违规(命名不佳、魔法数字、无用注释、缩进不一致),并按规范重写。🇨🇦 BC CP11"内联注释" / ON ICS3U B2.4
- Write a complete 4-column test plan (scenario / input / expected output / pass-fail) with at least three rows covering normal, boundary, and error cases for a grade calculator. 🇨🇦 ON ICS3U B4.4 / AB CSE1110 1.7为成绩计算器编写完整的 4 列测试计划(场景/输入/预期输出/通过失败),至少 3 行,涵盖正常、边界和错误情况。🇨🇦 ON ICS3U B4.4 / AB CSE1110 1.7
- Distinguish between syntax, logic, and runtime errors with one concrete Python example of each. State which type appears in a given buggy code snippet. 🇨🇦 AB CSE1110 3.1 / BC CP11用一个具体的 Python 示例区分语法、逻辑和运行时错误。说明给定有错误代码片段中出现哪种类型。🇨🇦 AB CSE1110 3.1 / BC CP11
- Write a properly documented Python function: docstring with parameters and return value, named constants instead of magic numbers, and at least one inline comment explaining WHY. 🇨🇦 BC CP12 "Standardized source code documentation"编写一个有适当文档的 Python 函数:包含参数和返回值的文档字符串、用命名常量替换魔法数字、至少一个解释为什么的内联注释。🇨🇦 BC CP12"标准化源代码文档"
- Name and distinguish all three maintenance types (corrective, adaptive, perfective) and give a real-world example of each for a school homework-tracker app. 🇺🇸 CSTA 3B-AP-22 / 🇨🇦 ON ICS3U B4.1命名并区分全部三种维护类型(纠正性、适应性、完善性),并为学校作业追踪应用举出每种类型的真实示例。🇺🇸 CSTA 3B-AP-22 / 🇨🇦 ON ICS3U B4.1
- Explain what each of the four Git commands does (
git init,git add,git commit,git push) and use them in a sentence describing a team project workflow. 🇨🇦 ON ICS4U B1.7 / BC CP12解释四个 Git 命令各自的作用(git init、git add、git commit、git push),并在一句话中描述团队项目工作流。🇨🇦 ON ICS4U B1.7 / BC CP12 - Identify which SDLC phase a given scenario belongs to (given 5 scenario cards, correctly place all five). Applicable to any curriculum. 🇨🇦 ON ICS3U B4 / 🇺🇸 CSTA 3B-AP-17识别给定场景属于哪个 SDLC 阶段(给定 5 张场景卡,正确放置所有五张)。适用于任何课程。🇨🇦 ON ICS3U B4 / 🇺🇸 CSTA 3B-AP-17
- Honors: ICS4U B1 / CSTA 3B-AP-20 Explain the pull-request code review workflow (feature branch → PR → review → merge) and state why it prevents untested code from entering the main codebase. 🇨🇦 ON ICS4U B1.7 / 🇺🇸 CSTA 3B-AP-20荣誉:ICS4U B1 / CSTA 3B-AP-20 解释拉取请求代码审查工作流(功能分支 → PR → 审查 → 合并),并说明为什么它能防止未经测试的代码进入主代码库。🇨🇦 ON ICS4U B1.7 / 🇺🇸 CSTA 3B-AP-20
What This Feeds Into本单元的去向
Software development process skills underpin every project you will build. The SDLC framework you learned here is the scaffold: requirements before design, design before code, code before testing, testing before deployment. The design tools (pseudocode, flowcharts, UML) resurface in later projects and courses. Version control with Git is widely used in professional programming and in many advanced programming courses.软件开发过程技能支撑你将构建的每一个项目。你在这里学到的 SDLC 框架是支架:需求先于设计,设计先于编码,编码先于测试,测试先于部署。设计工具(伪代码、流程图、UML)会在之后的项目和课程中再次出现。Git 版本控制在专业编程和许多高级编程课程中被广泛使用。
Within High School Computer Science.在 HS Computer Science 内部。
This is the last unit, and it gathers habits from the earlier ones. Control Flow (Unit 3) is where flowcharts and pseudocode come before the Python (the Design phase); Functions and Modular Design (Unit 4) formalises decomposition into callable sub-programs; Object-Oriented Programming Intro (Unit 8) uses UML class diagrams as its primary design tool. Apply the testing and version-control habits from this guide to every project from here on.这是最后一个单元,它汇集了前面各单元的习惯。控制流(第 3 单元)中流程图和伪代码先于 Python 出现(设计阶段);函数与模块化设计(第 4 单元)把分解正式化为可调用的子程序;面向对象编程入门(第 8 单元)使用 UML 类图作为主要设计工具。从现在起,请把本指南中的测试和版本控制习惯用在每个项目中。
AP feeder links.AP 衔接链接(本仓库中已有)。
AP CSP Big Idea 1 (Creative Development) covers the same ground as this guide: its learning objectives CRD-2.A through CRD-2.J concern program design, development, testing and debugging. The AP CSP Create Performance Task builds on this process, and the documentation skills in §6 apply to it. AP CSA (Java) builds on the same habits of design, testing and version control.AP CSP 大概念 1(创意开发)与本指南涉及相同的内容:其学习目标 CRD-2.A 至 CRD-2.J 涉及程序设计、开发、测试和调试。AP CSP 创作绩效任务建立在这一过程之上,§6 中的文档技能也适用于它。AP CSA(Java)建立在同样的设计、测试和版本控制习惯之上。
This is the ladder we coach students up: from these high school foundations into AP and IB, and on to first-year university. If you would rather have a guide for the next step than take it on trust, Dingrui Scholars tutors teach exactly this path in one-on-one sessions and small-group classes. A free assessment is the place to start.这正是我们陪伴学生攀登的阶梯:从这些高中基础,迈入 AP 与 IB,再走向大学一年级。如果你希望在下一步有人引路,而不是凭感觉前行,Dingrui Scholars 的导师正是沿着这条路径,以一对一辅导与小班课授课。欢迎从免费评估开始。
Common Questions常见问题
What are the stages of the software development life cycle?软件开发生命周期有哪些阶段?
The SDLC moves through analysing requirements, designing the solution with artifacts like flowcharts and pseudocode, implementing the code to coding standards, testing with a formal plan, documenting, and finally maintenance to fix bugs and add features after release.软件开发生命周期依次经过分析需求、用流程图和伪代码等成果设计方案、按编码规范实现代码、按正式计划测试、编写文档,最后是发布后修复漏洞和增加功能的维护阶段。
What makes a good software requirement?什么样的软件需求才算好?
A good requirement is specific and measurable enough to write a test case for, with a concrete action and a measurable outcome. Vague phrases like user-friendly, clean code, or fast database are not requirements because they cannot be tested.好的需求足够具体且可衡量,能为它写出测试用例,包含明确的动作和可衡量的结果。像用户友好、代码整洁或数据库快速这类含糊的说法不算需求,因为它们无法测试。
What are the basic Git commands for version control?版本控制中基本的 Git 命令有哪些?
git init creates a new repository in the current folder, git add stages a file for the next commit, git commit saves the staged changes, and git push uploads your local commits to a remote repository like GitHub so teammates can access your work.git init 在当前文件夹创建新仓库,git add 把文件暂存以备下次提交,git commit 保存暂存的改动,git push 把本地提交上传到 GitHub 等远程仓库,让队友能访问你的工作。
Syllabus alignment & how to use this guide大纲对照与使用说明
How to use this guide如何使用本指南
The software development life cycle is covered in all four curricula, but with different emphasis. Ontario ICS3U strand B4 lists seven SDLC phases (worded a little differently from §1) and asks for a formal test plan; that coverage aligns with §1, §2, and §5. BC Computer Programming 11 frames the entire programming course around the design cycle, making §3 (design) and §7 (collaboration) its core. Alberta builds SDLC skills into every module's outcome structure rather than one dedicated unit. US CSTA 3B-AP-16/22 and AP CSP Big Idea 1 (CRD) emphasise the iterative, collaborative nature of development, matching §7. The table below tells you which sections are core for your curriculum right now.软件开发生命周期在四套大纲中均有覆盖,但侧重点不同。安大略 ICS3U B 单元 B4 列出七个 SDLC 阶段(措辞与 §1 略有不同),并要求正式测试计划;这对应 §1、§2 和 §5。BC Computer Programming 11 将整个编程课程围绕设计周期展开,使 §3(设计)和 §7(协作)成为核心。阿尔伯塔将软件开发技能嵌入每个模块的结果结构中,而非单独的一个单元。美国 CSTA 3B-AP-16/22 和 AP CSP 大概念 1(CRD)强调开发的迭代性和协作性,对应 §7。下表告诉你当前哪些节属于你大纲的核心内容。
| If you are in…如果你在… | Focus on these sections重点学习 | Defer / lighter可推迟 / 减负 | Source依据 |
|---|---|---|---|
| 🇺🇸 US CSTA / AP CSP美国 CSTA / AP CSP | §1 (SDLC overview), §5 (testing, within CRD-2.A to CRD-2.J), §7 (collaboration, CRD-1.A to CRD-1.C). AP CSP Big Idea 1 maps directly to §2–§5 (design, prototyping, testing, debugging). CSTA 3B-AP-22 (modify and iterate) maps to §6 (maintenance).§1(SDLC 概览)、§5(测试,属于 CRD-2.A 至 CRD-2.J)、§7(协作,CRD-1.A 至 CRD-1.C)。AP CSP 大概念 1 直接对应 §2–§5(设计、原型制作、测试、调试)。CSTA 3B-AP-22(修改与迭代)对应 §6(维护)。 | Formal project management (§2 Gantt/scope docs) is AP CSP-lighter; emphasised more in Ontario ICS4U.正式项目管理(§2 甘特图/范围文档)在 AP CSP 中较轻;安大略 ICS4U 更为强调。 | CSTA K-12 and AP CSP: CSTA 3B-AP-16, 3B-AP-22; AP CSP Big Idea 1 (CRD) topics 1.1–1.4:CSTA 3B-AP-16、3B-AP-22;AP CSP 大概念 1(CRD)主题 1.1–1.4 |
| 🇨🇦 ON Grade 11: ICS3U安大略 11 年级:ICS3U | §1 through §6 in full: ICS3U B4.1 lists seven SDLC phases (see the note in §1 on how its wording differs). §3 (UML tools: B2.4), §5 (test plan: B4.4), §6 (documentation). ICS4U B1.7 adds version control (§7).§1 至 §6 完整学习:ICS3U B4.1 列出七个 SDLC 阶段(其措辞的差异见 §1 的说明)。§3(UML 工具:B2.4)、§5(测试计划:B4.4)、§6(文档)。ICS4U B1.7 增加版本控制(§7)。 | The Gantt chart and critical path in §2 (Worked Example 4) go beyond ICS3U; ICS4U strand B1.4 names Gantt and PERT charts (Grade 12).§2 中的甘特图与关键路径(例题 4)超出 ICS3U 的范围;ICS4U B 单元 B1.4 提到甘特图和 PERT 图(12 年级)。 | ON/BC Computer Studies 11-12: ICS3U B2.4, B4, B4.1, B4.4; ICS4U B1, B1.4, B1.7:ICS3U B2.4、B4、B4.1、B4.4;ICS4U B1、B1.4、B1.7 |
| 🇨🇦 BC: CP11 / CP12BC:CP11 / CP12 | §1 (design cycle Big Idea), §3 (design), §5 (test cases: CP11 verbatim), §7 (pair programming, collaboration tools: CP11/CP12 verbatim). CP12 adds standardized documentation (§6) and debugging tools.§1(设计周期大概念)、§3(设计)、§5(测试用例:CP11 原文)、§7(结对编程、协作工具:CP11/CP12 原文)。CP12 增加标准化文档(§6)和调试工具。 | Formal SDLC phase labelling (§1) is more Ontario/CSTA than BC; BC frames it through the design cycle Big Idea rather than a phase checklist.正式的 SDLC 阶段标注(§1)更多属于安大略/CSTA 的风格,而非 BC;BC 通过设计周期大概念而非阶段清单来框架化此内容。 | ON/BC Computer Studies 11-12: BC CP11 design cycle / test cases / pair programming; CP12 documentation / debugging tools:BC CP11 设计周期/测试用例/结对编程;CP12 文档/调试工具 |
| 🇨🇦 AB: CSE Project modules阿尔伯塔:CSE 项目模块 | §1 (SDLC framing: built into every module), §4 (implementation: CSE1110 outcome 2.1), §5 (testing: CSE1110 outcome 3.1). The iterative/incremental framing from CSE3120 outcome 2.2 and 3.1 underpins §1 and §7.§1(SDLC 框架:嵌入每个模块)、§4(实现:CSE1110 结果 2.1)、§5(测试:CSE1110 结果 3.1)。CSE3120 结果 2.2 和 3.1 的迭代/增量框架支撑 §1 和 §7。 | Project design and management skills are developed in the CSE Project modules (CSE1910/2910/3910), which are separate credits.项目设计与管理技能在 CSE 项目模块(CSE1910/2910/3910)中培养,这些模块是独立的学分。 | Alberta CTS Computing Science: CSE1110 outcomes 2.1, 3.1; CSE3120 outcomes 2.2, 3.1; CSE Project A/B/C/D descriptions:CSE1110 结果 2.1、3.1;CSE3120 结果 2.2、3.1;CSE 项目 A/B/C/D 描述 |
Once you have located your row, use the two cards below to calibrate your study pace.找到所在行后,用下面两张卡片决定推进速度。
Memorise three things: the seven SDLC phases in order (requirements, analysis, design, implementation, testing, documentation/deployment, maintenance); the three types of errors (syntax, logic, runtime); and what a test plan includes (scenario, input, expected output, actual output, pass/fail). Read every cram-cheat box. Skip the Git deep-dive in §7.背熟三件事:七个 SDLC 阶段的顺序(需求、分析、设计、实现、测试、文档/部署、维护);三种错误类型(语法、逻辑、运行时);测试计划包含的内容(场景、输入、预期输出、实际输出、通过/失败)。读每个速记框,跳过 §7 中的 Git 深入内容。
Always design before you implement: write requirements first, produce a design artifact (flowchart, pseudocode, or UML sketch), then write a test plan before touching a code editor. Ontario ICS3U B4.4 covers writing test plans with expected outputs, and AB CSE1110 outcome 1.7 covers testing for failure as well as success. §7 version control appears in Ontario ICS4U B1.7, so know the four core Git commands.永远先设计再实现:先写需求,产出设计制品(流程图、伪代码或 UML 草图),然后在打开代码编辑器之前写好测试计划。安大略 ICS3U B4.4 涉及编写包含预期输出的测试计划,AB CSE1110 结果 1.7 涉及对失败和成功情况都进行测试。§7 版本控制出现在安大略 ICS4U B1.7 中,所以要掌握四个核心 Git 命令。
git init, git add, git commit, git push) and the branch-merge workflow. The Honors chip marks the going-deeper box covering branching strategies and pull-request code review. That box maps to Ontario ICS4U B1.7 (version control) and CSTA 3B-AP-20 ("Use version control systems … in a group software project"). For ICS3U / CSE1110 / AP CSP, understanding what version control is and why it matters is the core level; the commands themselves are a useful extra.§7(协作与版本控制)从概念层面介绍 Git:四个命令(git init、git add、git commit、git push)和分支合并工作流。Honors 标记深入框,涵盖分支策略和拉取请求代码审查。该框对应安大略 ICS4U B1.7(版本控制)和 CSTA 3B-AP-20("在团队软件项目中使用版本控制系统……")。对于 ICS3U / CSE1110 / AP CSP,理解版本控制是什么及其重要性是核心层次;命令本身是有用的补充。