Software Engineering
Why does software that a thousand people change every day fail differently from a weekend's program?
The part opens at Garmisch in October 1968, where the NATO conference named the software crisis, and with the software on screen: this repository, 2,587 Python modules and 5,564 imports, with 5 import cycles and 2 imports against its layering. Parnas's keyword-in-context index is built twice, and one change touches three of five modules in the flowchart decomposition and one of six when each module hides a decision. Abstract types, contracts and Liskov's rule follow, with a Square that fails Rectangle's property on the first random trial. The repository's coupling is measured, SOLID and six patterns are stated with counterexamples, and then the part tests the tests: eight flaky tests turn 82% of runs red, a fuzzer crashes the Pebble assembler at 24 sites, and a suite that covers 77% of the statements kills only 62% of the mutants. The second half is about people and time: technical debt as a model, merge conflicts against integration interval, work in progress under Little's law, Conway's law, Brooks' law simulated with its condition, and estimates whose plan of medians is met 12% of the time. It ends with the profession's failures, Horizon and the 737 MAX, and with what evidence the field has, including models that write code.
What you need. The ability to read Python, and experience of writing a program of a few hundred lines.
- Mathematics, ideas and history
- Parnas' information hiding, abstraction and behavioural subtyping, coupling metrics, design patterns, testing and flakiness, refactoring, technical debt, code review, DORA, Conway's and Brooks' laws, estimation, the profession
- What we build or compute
- this repository's own dependency graph, measured
What you will be able to do
Degree
- Name the decision each module of a design hides, and predict which modules a given change touches.
- State a representation invariant and a contract, and show why Square is not a behavioural subtype of Rectangle.
- Explain why a test can pass alone and fail in a suite, and what a mutation score measures that coverage does not.
Graduate
- Compute afferent and efferent coupling and instability on an import graph, and find its cycles.
- Bisect a test order to find a polluter, and run mutation testing on a module.
- Simulate Brooks' law and a schedule of lognormal tasks, and read the tail.
Research
- Explain the oracle problem for machine-written patches, and why passing tests is an incomplete criterion.
- Propose a score for a test suite that predicts whether an accepted patch is correct, and validate it on mutants.
Industry
- Write a design document, keep changes small enough to review, and fix flaky tests rather than retry them.
- Limit work in progress, integrate daily, and estimate in ranges with a stated confidence.
- Read the DORA metrics without turning them into targets.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 22 min · Graduate 43 min · Research 46 min · Industry 36 min.
- 0The software crisis, and this repositoryDegree2 min
- 1Complexity, and Parnas' ruleDegree4 min
- 2Abstraction and contractsDegree4 min
- 3Coupling, measuredGraduate3 min
- 4Design, in the large and the smallDegree3 min
- 5Testing, and tests that lieDegree4 min
- 6Testing the testsGraduate3 min
- 7Changing code that worksIndustry3 min
- 8Review and processIndustry5 min
- 9TeamsIndustry3 min
- 10EstimatesIndustry3 min
- 11The professionDegree3 min
- 12Frontier: evidence, and machines that codeResearch3 min
- Recap, problems, and where this comes backAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
The software crisis, and this repositoryDegree2 min
In October 1968, about fifty people met in the Bavarian town of Garmisch for a NATO conference with a deliberately provocative title. Software Engineering. Building bridges was engineering; writing programs, so far, was not. The participants spoke of a software crisis: large systems arriving years late, far over budget, unreliable, and almost impossible to change. The most famous example was IBM's operating system for the System/360, which at its peak occupied more than a thousand people. Fred Brooks, who managed it, wrote a book about what went wrong, The Mythical Man-Month. Its best-known sentence is Brooks' law: adding manpower to a late software project makes it later. We will test that, and much else, with simulations and with data.
This part is about software as something large and long-lived, built and changed by many hands. So the first specimen is the software that made this series. Each square is one Python module of this repository, coloured by where it lives: the shared library, the scenes of each series, the tools and the tests. About two and a half thousand modules and six hundred thousand lines, joined by five and a half thousand imports. We will measure it like any other system: its dependencies, its cycles, the places where its own rules are broken. There are five import cycles, and two imports that run the wrong way between its layers. And it has a history: about a hundred and sixty commits in its first five days, every one of them recorded, which we will mine for a kind of coupling no import statement shows. It is not a large system by industrial standards, but it is large enough to show every problem in this part.
1Complexity, and Parnas' ruleDegree4 min
Eighteen years after Garmisch, Brooks wrote an essay called No Silver Bullet. He split the difficulty of software in two. Essential complexity lives in the problem itself: the tax code, the network protocol, the physics being simulated. No tool removes it. Accidental complexity lives in how we build: managing memory by hand, waiting for slow builds, untangling code. High-level languages, Part 13's compilers and Part 15's garbage collectors removed a great deal of it. Brooks argued that once the accidental part is small, no single technique can deliver a tenfold gain within a decade. What remains is the essential complexity, and the main tool for it is division: splitting a system into parts that can each be understood, built and changed on their own. But split along which lines?
In 1972 David Parnas answered with an experiment on paper, and we will run it for real. The program is a keyword-in-context index: take a list of titles, form every circular shift of each one, and print them all in alphabetical order, so that every word can be looked up in context. The obvious decomposition follows the flowchart: one module per processing step, input, shifting, sorting, output, all reading and writing shared tables of words and positions. Parnas' decomposition looks almost the same but cuts differently. One module, line storage, owns how lines are stored, and nobody else knows. Another owns how a circular shift is represented; another, when and how sorting happens. We wrote both, in this repository, and they produce the same thirty-one lines.
Now change one design decision, as Parnas did. Store each word as a number in a vocabulary, to save memory. In the flowchart design, three of the five modules read the word tables directly, so all three must be rewritten, sixteen lines in all. In Parnas' design, one module changes: line storage, nine lines. Nobody else knew how words were stored.
We made four of Parnas' changes to both programs and checked every variant against the original index. Changing the input format touches one module in both designs, because both kept reading input in one place. Storing shifts in full instead of as positions: three modules against one. Sorting on demand instead of all at once: two against one. Each time, the cost of a change is the number of modules that knew about the decision being changed.
Parnas stated the principle in one sentence. Begin with a list of difficult design decisions, or decisions likely to change, and design each module to hide one of them from the others. What a module promises is its interface; everything else is its secret. John Ousterhout calls the best modules deep: a small interface over a lot of functionality, like the handful of Unix calls, open, read, write, seek and close, in front of the whole file system of Part 34. Most of this part is variations on Parnas: contracts state the interface precisely, coupling measures how much leaks through it, and tests pin it down.
2Abstraction and contractsDegree4 min
Barbara Liskov and Stephen Zilles gave Parnas' idea a form a compiler can enforce. An abstract data type is known only by its operations; its representation is private. Here a set of integers is represented by a list. Two pieces of reasoning make such a type correct. The representation invariant says which lists are legal: sorted, with no repeats. The abstraction function says what a legal list means: the set of its elements. Every operation must preserve the invariant, and then the others may rely on it: size can simply return the length of the list, because the invariant guarantees there are no repeats. Liskov later received the Turing Award for this work.
Bertrand Meyer turned interfaces into contracts. A precondition is what the caller must guarantee: here, a positive amount no larger than the balance. A postcondition is what the function then guarantees in return: the balance went down by exactly that amount. An invariant holds before and after every operation. Contracts settle arguments: if a precondition fails, the caller has the bug; if a postcondition fails, the implementation does. They are the triples of Hoare logic, which Part 54 will prove, checked at run time instead: assertions, type checkers, and contract clauses in languages like Eiffel and Ada. Checking contracts costs time, so many teams check them in tests and debug builds and switch the expensive ones off in production; others keep them on, preferring a clear crash to silently wrong results.
Inheritance adds a trap. A square is a rectangle in geometry. So make Square a subclass of Rectangle, and keep the sides equal by changing both whenever either is set. A client that was written for rectangles expects that after setting width w and height h, the area is w times h. We tested that property the way QuickCheck does, on random inputs. On rectangles it held a thousand times out of a thousand. On squares it failed on the first try, and shrinking found the smallest failing case: width zero, height one, area one. Barbara Liskov and Jeannette Wing made the rule precise in 1994. A subtype may demand no more and promise no less than its parent, must keep its invariants, and must not add new ways of changing state. Square adds one: setting the width changes the height. In code, it is not a rectangle.
Contracts describe interfaces at one moment, but interfaces live for years. Inside is the documented behaviour. Around it is everything else a user can observe: timing, the text of error messages, the order in which a collection is iterated, rounding, even the bugs. Hyrum Wright, at Google, put it as a law: with enough users, every observable behaviour will be depended on by somebody, whatever the contract says. Changing any of it breaks someone. Semantic versioning tries to make change legible: the major number rises for incompatible changes, the minor for additions, the patch for fixes, and Part 41 will solve the constraint puzzles this creates. A real case: Python's dictionaries started keeping insertion order in version 3.6 as an accident of a new implementation. So much code came to rely on it that version 3.7 made it part of the language.
3Coupling, measuredGraduate3 min
This repository has a layered design, a rule that no file states but every file is supposed to obey. The library, explainer, holds the shared instruments: the Pebble machine, the simulators, the drawing helpers. The scenes, in videos, use the library. Over two thousand imports go downward, from scenes to library, as they should. And two go up. One library module, which loads the thirty novels, reaches into the first AI video to reuse its code. It works today; it means the library cannot be used without that video, and a change to the video can break every part that loads the novels. Tools and tests sit beside the library and depend on it too.
Robert Martin turned coupling into numbers. For each module count the modules that depend on it, the afferent couplings, and the modules it depends on, the efferent ones. Its instability is the second count over the total. A module that everything uses and that uses nothing is stable: changing it is expensive, so it should rarely need to change. Here is the distribution over this repository. Most modules, the scenes themselves, have instability one: they use the library and nothing uses them, so they are free to change. A few hundred sit near zero. These are the most depended upon: the library's packages, imported by hundreds of modules each, and importing almost nothing. That is Martin's stable dependencies principle in practice: depend in the direction of stability, never on something likely to change more often than you.
Strongly connected components, Part 18's algorithm, find the cycles. This repository has five. Four are inside single AI videos, where a compute script and its helpers import each other. The first is in the library itself: its root package, the narration engine and the voice-over scene import each other in a ring. A cycle fuses its modules into one: none can be tested, reused or understood alone, and the order in which they load starts to matter. The standard cure is dependency inversion. When high-level policy calls a low-level detail that also needs the policy, give the policy an interface and make the detail depend on that. Both arrows now point at the abstraction, and the cycle is broken.
Imports show only one kind of coupling. Version control shows another. Harald Gall and colleagues proposed in 1998 to look for files that change in the same commits. We mined this repository's history. Every commit that changed the project's instructions file also changed the series syllabus, and almost all of them the series plan. The reason is mundane: each of the three records how many parts are built. One fact stored in three places, so every new part edits all three, and forgetting one leaves them disagreeing. Refactoring books call it shotgun surgery. The cure is one source of truth from which the others are generated. Our own process has the smell this chapter teaches you to find.
4Design, in the large and the smallDegree3 min
Industry condensed decades of design advice into five letters, popularized by Robert Martin. Each is easiest to understand through the mistake it prevents. Single responsibility: a class that formats a report, queries the database and sends the email has three reasons to change. Open-closed: code that switches on a type must be edited for every new case. Liskov substitution is our square. Interface segregation: do not force every printer to implement fax. And dependency inversion is the cure for the cycles of the last chapter. They are heuristics, not laws. Each is Parnas' hiding seen from one side, and each can be overdone, into layers of indirection that hide nothing.
In 1994 four authors, the Gang of Four, catalogued design patterns: solutions that keep reappearing, given names so that people can talk about them. We have used many already. Strategy swaps an algorithm behind one interface, like the congestion controllers of Part 37. Observer notifies subscribers of changes. Visitor walks a fixed tree of types, as Part 13's compiler passes did. Adapter, decorator and factory wrap, extend and choose. Many patterns exist because the languages of 1994 lacked features. Peter Norvig showed that in a language with first-class functions, sixteen of the twenty-three become invisible or simpler: a strategy is just a function passed as an argument.
One tension underlies much of design, and Philip Wadler named it the expression problem. Picture a table: rows are kinds of data, here numbers, sums and products; columns are operations, evaluate, print, simplify. Every cell is some code. Object-oriented code stores the table by rows: each class holds its row. Adding a new kind of data is one new class, but adding an operation means editing every class. Functional code, with Part 14's algebraic data types, stores it by columns. A new operation is one function, but a new kind of data means editing every function. The problem is to allow both, without touching old code and without losing type safety. Type classes, object algebras and multimethods are partial answers; which axis your program will grow along is the real design decision.
Industry has also absorbed functional ideas. On the left, an order with two flags and an optional tracking number: eight combinations, including an order that is both paid and cancelled. On the right, a type with exactly the four shapes the business allows. Yaron Minsky's slogan: make illegal states unrepresentable, and a whole class of bugs cannot be written. Gary Bernhardt's design puts every decision in pure functions, which can be tested with plain values, and keeps input, output and time in a thin shell around them. And immutable values can be shared between threads, Part 33's hardest problem, and cached without fear.
5Testing, and tests that lieDegree4 min
Tests are how a team keeps an interface from silently changing. Mike Cohn's pyramid says how to spend them: many small unit tests that each check one module in milliseconds, fewer integration tests that wire real modules together, and a handful of end-to-end tests that drive the whole system as a user would. To test a module alone, its dependencies are replaced by doubles: a fake actually works, like an in-memory database; a stub returns canned answers; a mock records how it was called. Doubles make tests fast and repeatable, at a price: they can drift away from the real thing they imitate.
A flaky test passes and fails on the same code. Qingzhou Luo and colleagues studied hundreds of them in open-source projects and found the usual causes: waiting a fixed time for something asynchronous, tests that depend on the order they run in, time and dates, and assuming an order for unordered collections. We planted eight such tests among a hundred and eighty-one sound ones and ran the suite four hundred times in random orders. The victim of a polluted cache fails more than half the time in the suite and never alone; the test that needs a setter fails half the time in the suite and always alone. Eight flaky tests out of a hundred and eighty-nine turned more than four runs in five red. Automatic re-runs hide some failures, including the order bug, and teach everyone to ignore red. At Google's scale, John Micco reported in 2016 that about one and a half percent of all test runs were flaky, and almost one test in six had been flaky at some time.
When a test fails only after others, which one is to blame? In one failing order, a hundred and fifty-nine tests ran before the victim. Run the first half of them followed by the victim. If it still fails, the polluter is in that half; otherwise in the other. Halve again. Seven runs instead of a hundred and fifty-nine, and the culprit is the test that leaves an administrator in the shared cache: Part 16's binary search, applied to a test suite. The fixes are boring and effective: reset shared state in every test, wait for conditions rather than fixed times, inject the clock, and sort before comparing.
Tests check the inputs someone thought of. Fuzzing tries the ones nobody did. In 1990 Barton Miller fed random characters to Unix utilities and crashed about a quarter of them. We did the same to Pebble's assembler, with a little more care: twenty thousand random programs built from real instruction names and operand shapes. Its contract is to assemble the program or reject it with an error naming the line. Most programs were rejected cleanly. But more than seven thousand crashed, at twenty-four different places in the code. The smallest examples are embarrassing: an add with no operands, a dot-equ with nothing after it. Instead of a clean error, Python raises an index error from deep inside the assembler. Every unit test passes; none of them tried this. Coverage-guided fuzzers such as AFL and libFuzzer steer the random inputs toward code not yet reached, and have found thousands of security bugs in widely used software.
6Testing the testsGraduate3 min
Tests check the code; what checks the tests? The usual answer is coverage: the fraction of lines the tests run. But running a line is not checking it. A test that calls a function and ignores the answer covers every line it touches. In 1978 Richard DeMillo, Richard Lipton and Fred Sayward proposed a sharper measure. Make many small wrong versions of the program, mutants, each with one deliberate change: a less-than for a less-or-equal, a plus for a minus, a constant off by one. Then run the tests on each. If the tests fail, the mutant is killed. If they pass, it survives: a wrong program the suite cannot tell from the right one. A few survivors are equivalent, behaving exactly as the original does, and deciding which ones are is, by Rice's theorem from Part 25, undecidable in general.
We turned this on a real module of this repository: the assembler for Pebble, from Part 6, and its unit tests, which all pass. Our mutation tool rewrote the assembler's syntax tree one site at a time, comparisons, arithmetic, logic and integer constants, a hundred and forty-six mutants in all, and ran the tests on each. The tests run seventy-seven percent of the assembler's statements, which sounds respectable. But they kill only sixty-two percent of the mutants. Most survivors live on lines the tests never run: error paths and directives nobody tested. Ten are worse. They change lines the tests do run, and the tests still pass.
The ten are worth reading. One makes a dot-word directive reserve five bytes per word instead of four. The tests use dot-word, but never check an address that comes after one, so a broken assembler passes. Others make the jump and return pseudo-instructions overwrite the return-address register; no test looks at it afterwards. Each survivor is a missing test, and the remedy is to assert on effects rather than merely run code. Mutation testing used to be too slow for industry. Google now runs it inside code review, showing developers a few relevant surviving mutants on each change, and many of them write the missing test.
Coverage criteria form a ladder. Take one line with three conditions. Statement coverage needs a single test that runs it. Branch coverage needs the decision to go both ways: two tests. All combinations of the conditions would need eight, and in general two to the n. Between them sits MC/DC, modified condition and decision coverage: for each condition, a pair of tests in which only that condition changes and the decision changes with it. That needs only n plus one tests, here four, yet shows that every condition matters. Aviation's standard requires it for the most critical flight software. Coverage says what ran; mutation says what was checked. Use the first to find code nobody tested, and the second to find tests that check nothing.
7Changing code that worksIndustry3 min
Most of a programmer's working life is spent changing code that already works. William Opdyke's thesis of 1992 defined refactorings: changes of structure that provably preserve behaviour, done in small named steps. Here a price calculation is split by extracting two functions. Nothing a caller can observe has changed; the next change, a new kind of discount, now touches one small function. For code nobody understands, Michael Feathers' first step is to write characterization tests: record what the code does now, right or wrong, and keep that fixed while you restructure. Code smells, long functions, duplicated logic, a class that knows about everything, are hints of where to start; they are symptoms, not proofs.
Ward Cunningham compared shipping code you know is not right to borrowing money. We turned the metaphor into a small model. A team ships ten points of features a week on clean code. Every feature shipped in haste adds debt, and debt slows all later work: that is the interest. Time spent refactoring pays it back. A team that never refactors is ahead after a quarter and far behind after two years, crawling at a third of its first speed. Spending a fifth of the time on cleanup delivers the most. Spending more also loses. The shape is the lesson: debt is a loan, and like a loan it can be worth taking, if you know the rate and plan to repay.
Much of what the field knows about change rests on surprisingly little. A famous curve says a defect fixed in production costs a hundred times as much as one fixed in design. It goes back to Barry Boehm's data from a few large projects of the nineteen seventies. In 2016 Tim Menzies and colleagues looked at a hundred and seventy-one modern projects and found no such effect: the effort to fix an issue did not grow with the phase in which it was found. Laurent Bossavit traced several of the field's most quoted numbers back to their sources and found very little underneath. The habit to keep is to ask for the data behind any claim about how software is built, including the claims in this part.
8Review and processIndustry5 min
Before a change is merged, someone else reads it. Michael Fagan's inspections at IBM in the nineteen seventies were formal meetings that walked through code line by line, and they caught many defects before testing. Modern review is lighter: a diff and a conversation. When Alberto Bacchelli and Christian Bird studied it at Microsoft, developers said they reviewed to find defects, but most comments were about understanding the change, alternatives and style. The largest benefit was knowledge spreading through the team. Size matters: reviewers do well on a few hundred lines at a time, read at a few hundred lines an hour, and poorly beyond that. The mechanical part belongs to machines: formatters, linters, type checkers and the static analyses of Part 54, run on every change.
How should the work itself be organized? The waterfall, one phase after another from requirements to operation, is usually traced to Winston Royce's paper of 1970. But Royce drew it in order to criticize it: he called it risky and an invitation to failure, because testing comes last, when mistakes are most expensive to fix. The alternative that won is iterative: short cycles, each ending in working software that people can use and react to. Scrum organizes the cycles as sprints of a few weeks, each planned, demonstrated and reviewed; Kanban as a continuous flow of items across a board; and the Agile Manifesto of 2001, written by seventeen practitioners at a ski resort in Utah, gave the movement its name and its values: working software over documentation, and responding to change over following a plan.
How often should a developer's work be merged into everyone else's? We simulated ten people editing four hundred files, a few of them hot, six edits a day each, each on a branch merged back at a fixed interval. A conflict is two branches changing the same region of a file. Merging every hour, almost nothing conflicts. Daily, a third of merges conflict, lightly. Weekly, nearly every merge conflicts, with eleven clashes to resolve. And per week of work, the conflicts keep growing as branches live longer: three a week for daily merges, fifteen for two-week branches. That is the argument for continuous integration, Kent Beck's and Martin Fowler's practice of merging to the main line at least daily, with tests run on every merge: small, frequent merges are cheaper in total, not just individually.
Kanban's central rule is a limit on work in progress, and Part 31's queueing explains why. We simulated four people receiving new items at random, eight every ten days on average, each needing four days of work, where juggling several items costs a little focus for each extra one. With no limit, everyone starts everything: over a thousand items end up in progress, output collapses, and an item takes years. With a limit of eight, throughput matches the arrivals and an item started is done in about six days. Tighter limits shorten that further, while the wait in the backlog grows: from request to done stays about ten days. It is Little's law, L equals lambda W: at a given throughput, the time each item spends in progress is proportional to the number in progress. Stop starting; start finishing.
Can delivery be measured at all? Nicole Forsgren, Jez Humble and Gene Kim proposed four numbers, from years of surveys of tens of thousands of professionals. How often a team deploys; how long a change takes from commit to production; what fraction of changes cause a failure; and how long it takes to restore service. In their 2019 report the elite teams deployed many times a day, shipped changes within a day, failed on at most fifteen percent of them and recovered within an hour. The striking finding is that speed and stability were not a trade-off: the teams that deployed most often also failed least. Small, frequent changes are easier to review, test and undo. And a caution from the economist Charles Goodhart: once a measure becomes a target, it stops being a good measure.
9TeamsIndustry3 min
In 1968 Melvin Conway observed that organizations produce systems shaped like themselves. Three teams, connected the way their people talk, build three modules connected the same way. Teams that never talk produce modules that do not fit, and a module owned by three teams changes slowly. Companies now use the law on purpose, the inverse Conway manoeuvre: decide the architecture first, then draw the teams to match it, one team for each service. There is evidence: a study of Windows Vista found that measures of the organization, how many people and teams touched a component, predicted which components would fail better than measures of the code did.
Brooks gave the arithmetic behind his law. Work can be split among n people, but if every pair must coordinate, there are n times n minus one over two channels: three for three people, ten for five, twenty-eight for eight, sixty-six for twelve. The work shrinks like one over n; the talking grows like n squared. Hence small teams with narrow interfaces between them, which is Parnas' principle applied to people, and Amazon's rule that a team should be small enough to feed with two pizzas.
Is Brooks' law true? We built a model with his mechanisms and nothing else. Six people and a hundred and twenty person-months of work. Newcomers need six months to reach full speed, and while they learn they take half the time of an experienced colleague; every pair pays a small tax for coordination. Without changes the project ends in month twenty-two. Add four people in month two, and it ends in month eighteen. Add the same four in month sixteen, with less time left than their ramp-up, and it ends later than if nobody had come. So the law holds, with a condition Brooks implied: it applies when the project is already late, and the newcomers cannot become productive before the end. And from the start, more people help until coordination dominates: in this model a team of twenty-four is fastest, and forty is slower.
Conway's law has a darker corollary: knowledge lives in people. A project's truck factor is the smallest number of people whose loss would stall it, because nobody else understands their code. Guilherme Avelino and colleagues estimated it for a hundred and thirty-three popular open-source projects: almost two thirds had a truck factor of one or two. The remedies are the ones this part keeps meeting: review spreads knowledge, documented interfaces and explanatory tests preserve it, and rotating who changes what keeps it shared. And a lone maintainer is also a security risk. In 2024 a backdoor was found in xz, a compression library present on most Linux systems; its author, overworked and alone, had been befriended over years by an attacker who became co-maintainer. Part 61 returns to it.
10EstimatesIndustry3 min
Estimates fail in a consistent direction, and a picture of one task explains much of it. How long a task takes is skewed: it can finish a little early, or very late, when something unexpected turns up. A lognormal shape fits such durations well. If the most likely value, the median, is five days, the mean is six, because of the long right tail. An honest estimate gives the median; the schedule experiences the mean. And people anchor on the best case of the task in front of them rather than on how long similar tasks took before: Daniel Kahneman and Amos Tversky called it the planning fallacy. It survives experience: people who know their last projects ran late still expect this one to be on time.
Now plan a project of twenty such tasks, each with a median of five days, and simulate it a hundred thousand times. Done one after another, the plan says a hundred days. With a modest spread the project meets the plan only about a quarter of the time; with the spread we drew, one time in eight; with a wide spread, one in twenty-five, and the bad cases run to two and a half times the plan. Splitting the work into parallel streams makes it worse: the project ends when its slowest stream ends, a maximum, like the fan-out tail of Part 39. With four streams the plan is met one time in a hundred.
Uncertainty also has a shape over the life of a project. Barry Boehm, and later Steve McConnell, summarized it as a cone. At the first idea, the final effort is anywhere from a quarter of the estimate to four times it. By the time the product is defined, half to double; with requirements complete, within fifty percent; with the design detailed, within ten. The cone narrows only as decisions are actually made, not as time passes. A project that defers its decisions stays at the wide end however long it runs.
What helps? Give a range, or a percentile, instead of a date: eighty percent likely by the fifteenth. Bent Flyvbjerg's reference-class forecasting starts from how long similar projects actually took, before looking at the details of this one. When the date is fixed, cut scope rather than quality, and re-estimate from the throughput you have actually measured.
11The professionDegree3 min
Almost every program written today is mostly other people's code, and that code comes with licenses. Permissive licenses, like MIT, BSD and Apache, let anyone use, change and sell the code, asking mainly that the notice be kept. Weak copyleft, like the LGPL, keeps changes to those particular files open. The GPL, Richard Stallman's copyleft, requires anyone who distributes a derived program to share its source on the same terms, and the AGPL extends that to programs offered as a service. These are legal obligations, and builds check them, as Part 41 will. And there is an economic oddity: code that much of industry depends on is often maintained by a few volunteers. When the Heartbleed bug was found in OpenSSL in 2014, the library that secured a large part of the web was being maintained by a handful of people.
Engineering ethics is not abstract. From 1999, the British Post Office's Horizon accounting system showed shortfalls at branch counters, and the Post Office prosecuted more than nine hundred sub-postmasters for theft and false accounting. Courts presumed that the computer was right. In 2019 a High Court judgment found that Horizon had bugs, errors and defects capable of causing such shortfalls. Convictions have since been overturned, some after the people convicted had died. In 2018 and 2019, two Boeing 737 MAX aircraft crashed, killing three hundred and forty-six people, after flight-control software acted on a single faulty sensor, in a system that pilots had been told too little about. The lessons are this part's own: evidence over assumption, honest reviews of risk, and no single point of failure, whether a sensor or a presumption.
A profession has obligations beyond the code. Privacy by design: collect only the data a purpose needs, use it only for that purpose, and delete it when done, principles that the European Union's data protection regulation made law in 2018. Accessibility: software that works with screen readers, keyboards alone and captions, which many countries require and every user benefits from. Safety: in the nineteen eighties the Therac-25 radiation machine gave massive overdoses to patients, after software, with a race condition of the kind Part 33 studied, replaced the hardware interlocks of earlier models. Nancy Leveson's investigation is still required reading. The ACM's Code of Ethics asks computing professionals to contribute to society, avoid harm, be honest, respect privacy, and review systems and their risks thoroughly. None of this is separate from engineering: privacy is a requirement like latency, accessibility a requirement like correctness, and the safest systems are those whose designers assumed that their own code, like every other code, contains bugs.
12Frontier: evidence, and machines that codeResearch3 min
Software engineering is still building its evidence base. Controlled experiments are expensive and small: a few dozen students for a few hours stand in for professionals working over years. Mining software repositories gives scale, millions of commits, reviews and bug reports, but mostly correlations. Some findings have held up well, and some can be checked in minutes on any codebase. Natural experiments, preregistered studies and replications are arriving, late, as they did in medicine and psychology.
Here is a finding from that evidence base that we can replicate in a minute. Train a trigram model, which predicts each word from the two before it, on four fifths of the thirty novels, and measure its surprise on the last fifth: about eight bits per word. Do the same on the Python code of this repository's library, token by token: four and a half bits. Code is far more predictable than prose. Abram Hindle and his colleagues found the same in 2012 for Java and C, and called it the naturalness of software. It is why code completion works, and it is the observation that grew into today's code-writing models.
Programs that write programs need the same scrutiny as people do. OpenAI's HumanEval of 2021 posed a hundred and sixty-four small functions, each with tests. Sample n programs from a model, count the c that pass, and this formula estimates the chance that at least one of k attempts would. SWE-bench, in 2023, raised the bar to real issues from GitHub projects: an agent's patch counts as a fix if the tests the human developers wrote for that issue pass. But tests are an incomplete oracle. Later audits found accepted patches that were wrong, and benchmark problems that had leaked into the models' training data. Our own measurements show why. The tests of our assembler, which pass, also pass on many slightly broken versions of it, as the mutation chapter showed. Any of those, submitted as a patch, would be scored as correct.
Where the field is. The oracle problem: when tests are incomplete, how can a machine judge whether a patch is right? Comparing against other implementations, writing specifications, and scoring tests by the mutants they kill all help, and none is complete. Measuring productivity: what does a tool, a process or an AI assistant really change, measured in the field rather than by asking people how they feel? Maintainability: a number that predicts how expensive code will be to change better than its size already does. And flaky tests: predicting them from their code, and repairing them automatically. This part's research problem asks for a score of a test suite that predicts whether a patch it accepts is really correct, checked on patches whose correctness we know: our assembler's mutants.
Recap, problems, and where this comes backAll tracks3 min
What we built in this part. Parnas' index, built two ways, and changes that cost three modules or one. Abstract types, contracts, and a square that is not a rectangle. This repository measured: its layers, its two upward imports, its five cycles, and the stability of its core. SOLID, patterns and the expression problem. Flaky tests found and bisected, a fuzzer that crashed our assembler twenty-four ways, and a mutation score that coverage hid. Code shown to be more predictable than prose. Debt as a model, and evidence that much folklore lacks. Little's law for work in progress, Conway's law, Brooks' law with its condition, and estimates with their tails.
Where this comes back. Part 41 builds version control and build systems, which are this part's dependency graphs made into machines. Part 43 designs the interfaces between services and the teams behind them. Part 44 delivers software continuously and measures it. Part 50 handles incidents, and Part 54 replaces tests with proofs where proofs are affordable.
In practice. Before large changes, write a design document: the problem, the options considered, and the decision, and review that before the code. Name the secret each module hides, and keep its interface small. Write many fast tests and few slow ones, and fix flaky tests instead of retrying them. Keep changes small so that review is quick, and let machines check the style. And estimate in ranges, cutting scope rather than quality when time runs out.
Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: write the tests that kill the ten survivors on lines our tests already run, and measure the new score. The last, marked with a star, is a research problem: a score for test suites that predicts whether a patch they accept is really correct.
Next time, Part 41: version control, builds and dependencies. Git turns out to be a Merkle graph of content-addressed objects; merging is a three-way comparison with a common ancestor; a build system is an incremental computation over a graph; and choosing versions of dependencies is NP-complete.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Part 41 turns this part's dependency graphs into machines: version control and build systems. Part 43 designs the interfaces between services and the teams behind them, Part 44 delivers software continuously and measures it, Part 50 handles incidents, and Part 54 replaces tests with proofs where proofs are affordable.
Key results
The part's results in one place, for revision.
Try it
Lab 40 · What a change costs: Parnas's modules, Brooks' law, and estimates
Build the keyword-in-context index of a random text with both of Parnas's decompositions, apply his four changes to each, and count the modules whose source had to change while the index stays the same. Then run the part's two process models: four people added to a six-person project at different months, and twenty lognormal tasks planned at their medians.
python -m videos.cs.labs 40
needs numpy, scipy, matplotlib · download lab40.py ·
source on GitHubchange: store words packed flowchart modules 3 of 5 (16 lines) hidden decisions 1 of 6 (9 lines)
change: change the input format flowchart modules 1 of 5 (2 lines) hidden decisions 1 of 6 (2 lines)
change: store shifts in full flowchart modules 3 of 5 (21 lines) hidden decisions 1 of 6 (12 lines)
change: alphabetize on demand flowchart modules 2 of 5 (8 lines) hidden decisions 1 of 6 (12 lines)
six people, nobody added finish in month 22.3 (120 / (6 x 0.9) = 22.2)
four added in month 2, and in month 16 month 17.8, and month 22.6 the film: 17.8 and 22.6
20 tasks, sigma = 0.3: on time 26.8% (the film: 27%) P80 111 days against a plan of 100 mean task 5.23 = 5 e^(sigma^2/2) = 5.23
20 tasks, sigma = 0.6: on time 12.0% (the film: 12%) P80 134 days against a plan of 100 mean task 5.99 = 5 e^(sigma^2/2) = 5.99
20 tasks, sigma = 1.0: on time 3.9% (the film: 4%) P80 199 days against a plan of 100 mean task 8.25 = 5 e^(sigma^2/2) = 8.24
Hiding one decision per module kept every change inside one module; people added late cost more than they give (worst when added in month 19); and a plan that adds up medians is met about one time in eight when tasks vary by a factor of e^0.6.
The code (90 lines; it asserts its own result)
"""Lab 40: apply Parnas's four changes to both KWIC decompositions, then test Brooks' law and a schedule's tail."""
from videos.coursekit import labs
import math
import numpy as np
from explainer.cs.se import kwic
from explainer.cs.se import process
TITLE = "What a change costs: Parnas's modules, Brooks' law, and estimates"
GOAL = ("Build the keyword-in-context index of a random text with both of Parnas's decompositions, apply his four "
"changes to each, and count the modules whose source had to change while the index stays the same. Then run "
"the part's two process models: four people added to a six-person project at different months, and twenty "
"lognormal tasks planned at their medians.")
TASKS = [
"Set ramp=1.0 and mentor=0.0 in process.brooks (newcomers productive at once). Until which month does adding four people still help?",
"Plan each task at its mean instead of its median (multiply the plan by exp(sigma^2 / 2)). How often is the project on time now?",
"Raise channel_cost from 0.02 to 0.04. Which team size finishes first from the start, and why is it smaller?",
]
WORDS = "pebble gate adder stack queue graph proof cache packet clock ledger novel index shift module secret".split()
SIGMAS = (0.3, 0.6, 1.0)
FILM_ON_TIME = (0.27, 0.12, 0.04)
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# Parnas: the same index from both decompositions, before and after each change
text = "\n".join(" ".join(rng.choice(WORDS, size=int(rng.integers(2, 6)))) for _ in range(8))
e = kwic.experiment(text)
n_shifts = sum(len(line.split()) for line in text.splitlines())
assert len(e["index"]) == n_shifts, "one index line per circular shift"
for r in e["rows"]:
d1, d2 = r["d1"], r["d2"]
lab.row(f"change: {r['change']}", f"flowchart modules {d1['n']} of {d1['of']} ({d1['lines']} lines) "
f"hidden decisions {d2['n']} of {d2['of']} ({d2['lines']} lines)")
assert d1["same_output"] and d2["same_output"], "every variant still prints the same index"
assert d2["n"] == 1, "with one secret per module, each change stays inside one module"
touched = [r["d1"]["n"] for r in e["rows"]]
assert sorted(touched) == [1, 2, 3, 3], "the flowchart decomposition spreads three of the four changes"
# Brooks: 120 person-months, six people, four more added at month m
base = process.brooks()
months = np.arange(0, 22.5, 1.0)
finish = np.array([process.brooks(add_at=float(m), add=4) for m in months])
worst = months[int(np.argmax(finish))]
lab.row("six people, nobody added", f"finish in month {base:.1f} (120 / (6 x 0.9) = {120 / 5.4:.1f})")
lab.row("four added in month 2, and in month 16", f"month {finish[2]:.1f}, and month {finish[16]:.1f} the film: 17.8 and 22.6")
assert abs(base - 120 / 5.4) < 0.1, "the baseline is work over six people's output, less five channels each"
assert finish[2] < base - 3 and finish[16] > base, "added early they help; added late they make the project later"
assert process.channels(10) == 45 and process.channels(6) == 15, "n(n - 1)/2 channels"
sizes = (2, 4, 6, 8, 12, 16, 24, 32, 40)
from_start = [process.brooks(team=n) for n in sizes]
assert sizes[int(np.argmin(from_start))] == 24, "from the start, 24 people is fastest; more is slower again"
# estimates: twenty lognormal tasks, plan = the sum of the medians
on_time = []
for sigma, film in zip(SIGMAS, FILM_ON_TIME):
s = process.schedule(sigma=sigma, trials=20_000, seed=seed)
on_time.append(s)
lab.row(f"20 tasks, sigma = {sigma}: on time", f"{s['on_time']:.1%} (the film: {film:.0%}) P80 {s['p80']:.0f} days against a plan of 100 "
f"mean task {s['mean_task']:.2f} = 5 e^(sigma^2/2) = {5 * math.exp(sigma ** 2 / 2):.2f}")
assert abs(s["on_time"] - film) < 0.02, "the plan of medians is rarely met"
assert abs(s["mean_task"] - 5 * math.exp(sigma ** 2 / 2)) < 0.03 * (1 + 3 * sigma), "a lognormal's mean exceeds its median"
assert on_time[0]["on_time"] > on_time[1]["on_time"] > on_time[2]["on_time"]
lab.note = ("Hiding one decision per module kept every change inside one module; people added late cost more "
f"than they give (worst when added in month {worst:.0f}); and a plan that adds up medians is met "
"about one time in eight when tasks vary by a factor of e^0.6.")
fig, ax = labs.figure(2, size=(11, 4.4))
names = ["store words\npacked", "change the\ninput format", "store shifts\nin full", "alphabetize\non demand"]
order = ["store words packed", "change the input format", "store shifts in full", "alphabetize on demand"]
rows = {r["change"]: r for r in e["rows"]}
x = np.arange(4)
ax[0].set_axisbelow(True)
ax[0].bar(x - 0.2, [rows[c]["d1"]["n"] for c in order], 0.4, color=labs.RED, label="flowchart decomposition (5 modules)")
ax[0].bar(x + 0.2, [rows[c]["d2"]["n"] for c in order], 0.4, color=labs.GREEN, label="one hidden decision each (6 modules)")
ax[0].set(title="Parnas's KWIC: modules a change touches", ylabel="modules whose source changed", xticks=x,
xticklabels=names, ylim=(0, 4.4), yticks=[0, 1, 2, 3])
ax[0].legend(loc="upper right")
ax[1].plot(months, finish, color=labs.GOLD, marker="o", ms=3.5, label="four people added in month m")
ax[1].axhline(base, color=labs.BLUE, ls="--", label=f"nobody added: month {base:.1f}")
ax[1].fill_between(months, base, finish, where=finish > base, color=labs.RED, alpha=0.3, label="Brooks' law: later")
ax[1].set(title="Brooks' law, with its condition", xlabel="month m in which the four join", ylabel="month the project finishes")
ax[1].legend(loc="lower right")
lab.fig = fig
return lab
Now change it
- Set ramp=1.0 and mentor=0.0 in process.brooks (newcomers productive at once). Until which month does adding four people still help?
- Plan each task at its mean instead of its median (multiply the plan by exp(sigma^2 / 2)). How often is the project on time now?
- Raise channel_cost from 0.02 to 0.04. Which team size finishes first from the start, and why is it smaller?
Problems, with solutions
Try each problem before opening its solution.
-
Parnas' modules. For the second decomposition, list the decision each module hides, and predict which modules each of the four changes touches.
Solution
Line Storage hides how words and lines are represented; Input hides the input format; the Circular Shifter hides how a shift is represented; the Alphabetizer hides when and how ordering is computed; Output hides the output format; Master hides the order of the calls. Packing words is a Line Storage decision, the input format an Input decision, storing shifts a Shifter decision, sorting on demand an Alphabetizer decision: one module each, as measured. In the flowchart design the word tables and the shift list are shared, so every module that reads them knows the representation: 3, 1, 3 and 2 modules.
-
Behavioural subtyping. State the rules for pre- and postconditions, and show that a stronger precondition breaks a client.
Solution
S's method m is a valid override of T's when pre_T ⇒ pre_S (the subtype accepts at least what the supertype did) and post_S ⇒ post_T (it promises at least as much). Suppose T.withdraw requires 0 < a ≤ balance and S.withdraw requires 0 < a ≤ balance − 100. A client proved correct against T calls withdraw(balance) on an S object; T's precondition holds, S's fails, and the call raises (or misbehaves), so substituting S broke a correct client.
-
Little's law. Prove L = λW for a system that starts and ends empty.
Solution
Let N(t) be the number in the system over [0, T], and item i spend W_i inside. The area A = ∫ N(t) dt counted vertically is the sum over items of their time inside, A = Σ W_i. Then A/T = (n/T)(Σ W_i / n), that is L = λW, with L = A/T the average number in the system, λ = n/T the throughput and W the mean time inside. In the Kanban table, a limit of 8 gives 5.37 items in progress at 0.796 a day, so W = 6.7 days by the law against 6.3 measured (the difference is the warm-up period that the measurement excludes).
-
Parallel streams. With k independent streams, show P(on time) = ∏ P(stream i on time).
Solution
The project is on time iff every stream is: {max_i T_i ≤ D} = ∩_i {T_i ≤ D}, and for independent streams the probability of an intersection is the product. Each of our four streams has five tasks and a plan of 25 days; one stream meets it with probability p ≈ 0.31, so all four with p⁴ ≈ 0.009, matching the simulated 1%.
-
Build. Kill the ten surviving mutants on lines the tests run.
Solution
Solution sketch. For
.word: assemble.word 1, 2followed by a label and assert the label's address is 8. Forjandret: setrato a known value, executej(and acallfollowed byret), and assertraafterwards. For thex + 4constant expressions: assemblela a0, x+4and check the immediate. Re-running the mutation tool should leave only mutants on unexecuted lines, which need tests of the error paths (and expose the fuzzer's crashes: those lines raiseIndexErrorinstead ofAsmError). -
★ Research. A test-adequacy score that predicts whether an accepted patch is correct.
Discussion. Open. Mutation score measures a suite's power to reject wrong programs near the original, which is the relevant distribution for patches; coverage does not. A research programme: generate patches with known correctness (mutants, and mutants of the fixed program), measure how often each suite accepts a wrong one, and test whether the mutation score, or a weighted version of it (by mutant type or by distance to the patch), predicts acceptance of wrong real patches, for example on SWE-bench tasks.
Notes and sources
Glossary
- essential / accidental complexity — difficulty inherent in the problem / introduced by the means of building.
- information hiding, interface, secret — a module hides one design decision; its interface is what it promises.
- abstract data type, representation invariant, abstraction function — a type known by its operations; which representations are legal; what a legal one means.
- design by contract — preconditions, postconditions and invariants as the terms of an interface.
- behavioural subtyping (Liskov substitution) — a subtype demands no more and promises no less.
- Hyrum's law — every observable behaviour of a widely used interface becomes depended on.
- afferent / efferent coupling, instability — dependents / dependencies; I = Ce / (Ca + Ce).
- dependency inversion — high and low levels both depend on an abstraction owned by the high level.
- logical coupling, shotgun surgery — files that change together; one change requiring edits in many places.
- expression problem — extending both data variants and operations without editing existing code.
- test double: fake, stub, mock — working stand-in; canned answers; recorded expectations.
- flaky test, polluter, victim — passes and fails on the same code; a test that leaves state; one that suffers.
- mutation testing, mutation score, equivalent mutant — wrong versions that tests should reject; the fraction rejected; a change with no observable effect.
- MC/DC — each condition shown to affect the decision independently.
- fuzzing — generating many random or mutated inputs to find crashes.
- refactoring, characterization test, technical debt — behaviour-preserving change; a test of current behaviour; the future cost of expedient design.
- Conway's law, Brooks' law, truck factor — systems mirror communication; adding people late delays; how few departures would stall a project.
- WIP limit, lead time, cycle time — a cap on work started; request to done; start to done.
- DORA metrics — deployment frequency, lead time for changes, change failure rate, time to restore.
- planning fallacy, cone of uncertainty — optimism about one's own plans; estimate error narrowing with decisions.
- copyleft — a license requiring derived works to be shared on the same terms.
- pass@k — the probability that at least one of k sampled programs passes the tests.
Sources
- F. Brooks, The Mythical Man-Month (1975; anniversary edition with "No Silver Bullet", 1995).
- P. Naur and B. Randell (eds.), Software Engineering: Report of a Conference Sponsored by the NATO Science Committee, Garmisch, 1968 (1969).
- D. Parnas, "On the criteria to be used in decomposing systems into modules", CACM 1972.
- B. Liskov and S. Zilles, "Programming with abstract data types", 1974; B. Liskov and J. Wing, "A behavioral notion of subtyping", TOPLAS 1994; B. Meyer, Object-Oriented Software Construction (1988).
- J. Ousterhout, A Philosophy of Software Design (2018); R. Martin, Agile Software Development (2002); E. Gamma, R. Helm, R. Johnson and J. Vlissides, Design Patterns (1994); P. Wadler, "The expression problem", 1998.
- T. Winters, T. Manshreck and H. Wright, Software Engineering at Google (2020).
- Q. Luo, F. Hariri, L. Eloussi and D. Marinov, "An empirical analysis of flaky tests", FSE 2014; W. Lam et al., "iDFlakies", ICST 2019; J. Micco, "Flaky tests at Google and how we mitigate them", 2016.
- R. DeMillo, R. Lipton and F. Sayward, "Hints on test data selection", Computer 1978; Y. Jia and M. Harman, "An analysis and survey of the development of mutation testing", TSE 2011; G. Petrović and M. Ivanković, "State of mutation testing at Google", ICSE SEIP 2018; B. Miller, L. Fredriksen and B. So, "An empirical study of the reliability of UNIX utilities", CACM 1990.
- W. Opdyke, Refactoring Object-Oriented Frameworks (thesis, 1992); M. Fowler, Refactoring (1999); M. Feathers, Working Effectively with Legacy Code (2004); W. Cunningham, "The WyCash portfolio management system", 1992.
- T. Menzies, W. Nichols, F. Shull and L. Layman, "Are delayed issues harder to resolve?", EMSE 2016; L. Bossavit, The Leprechauns of Software Engineering (2015).
- M. Fagan, "Design and code inspections", IBM Systems Journal 1976; A. Bacchelli and C. Bird, "Expectations, outcomes, and challenges of modern code review", ICSE 2013.
- W. Royce, "Managing the development of large software systems", 1970; N. Forsgren, J. Humble and G. Kim, Accelerate (2018).
- M. Conway, "How do committees invent?", Datamation 1968; N. Nagappan, B. Murphy and V. Basili, "The influence of organizational structure on software quality", ICSE 2008; G. Avelino et al., "A novel approach for estimating truck factors", ICPC 2016; H. Gall, K. Hajek and M. Jazayeri, "Detection of logical coupling based on product release history", ICSM 1998.
- D. Kahneman and A. Tversky, "Intuitive prediction: biases and corrective procedures", 1979; B. Boehm, Software Engineering Economics (1981); S. McConnell, Software Estimation (2006); B. Flyvbjerg, "From Nobel prize to project management", 2006.
- N. Leveson and C. Turner, "An investigation of the Therac-25 accidents", Computer 1993; Bates v Post Office Ltd (No 6: Horizon Issues), High Court, 2019; ACM Code of Ethics and Professional Conduct (2018).
- A. Hindle, E. Barr, Z. Su, M. Gabel and P. Devanbu, "On the naturalness of software", ICSE 2012; M. Chen et al., "Evaluating large language models trained on code", 2021; C. Jimenez et al., "SWE-bench", ICLR 2024.
About this partfrom its README
Part 40 of a sixty-one-part course in computer science (see the series plan and the syllabus), the first part of Act VIII, Building Software, and the series' third review part. What one person writes in a weekend fails differently from what a thousand people change every day. The discipline named at the 1968 NATO conference is about managing that complexity: modules that hide decisions, interfaces that survive change, tests that pin behaviour down, and teams whose structure becomes the system's. Wherever a claim can be tested we test it, often on this repository itself.
The instruments are in explainer/cs/se/ (tested in tests/test_cs40_se.py):
kwic.py: Parnas's keyword-in-context index as real code in both decompositions (the flowchart with shared tables; one module per hidden decision), four of Parnas's changes applied to each, every variant run and compared, and the modules and lines touched counted.repo.py: this repository's Python import graph (modules, edges, Tarjan's strongly connected components, imports across layers, afferent and efferent coupling and Martin's instability); its git history (commits, churn) and logical coupling (files changed in the same commits); a trigram model's cross-entropy on its code and on the thirty novels.testing.py: a suite with eight planted flaky tests (asynchronous waits, a polluter and its victim, a hidden setter, time, unordered collections) run in random orders, retries, and bisection for the polluter; a QuickCheck- style property test with shrinking (Square against Rectangle); an AST mutation tool with time limits, run against the Pebble assembler and this repository's tests; statement coverage by tracing; a grammar-aware fuzzer for the assembler.process.py: Brooks' law as a simulation (coordination, ramp-up, mentoring); Monte Carlo schedules of lognormal tasks; Kanban work-in-progress limits and Little's law; a model of technical debt; merge conflicts against how often branches are integrated.
Chapter notes
- Hook. Garmisch, October 1968: the software crisis, OS/360, Brooks' law. The software you are watching: 2,587 Python modules, 614,570 lines, 5,564 imports, 5 import cycles, 2 imports against the layering.
- 1. Complexity, and Parnas' rule. Essential and accidental complexity ("No Silver Bullet"). KWIC built twice (31 index lines, identical): storing words packed touches 3 of 5 modules (16 lines) against 1 of 6 (9 lines); storing shifts in full 3 against 1; sorting on demand 2 against 1; the input format 1 and 1. Information hiding; deep modules.
- 2. Abstraction and contracts. Abstract data types, representation invariants and abstraction functions; design by contract; Square fails the Rectangle property on the first random trial, shrunk to (w, h) = (0, 1); Liskov and Wing's rules. Hyrum's law; semantic versioning; Python's dictionary order.
- 3. Coupling, measured. Layers: 2,292 imports from scenes to library, 2 the wrong way
(
explainer.ai.novels→videos.ai.ai1). Instability: 1,694 modules at I ≈ 1, 232 near 0; the most depended-upon packages. Five cycles (one in the library's root); dependency inversion. Logical coupling in the history: the instructions file, the syllabus and the series plan change together because they store one fact three times. - 4. Design. SOLID with a counterexample for each; six patterns where the series used them; Norvig's 16 of 23; the expression problem; illegal states unrepresentable; a functional core in an imperative shell.
- 5. Testing. The pyramid and test doubles. 189 tests with 8 flaky, 400 random orders: 82% of runs red, 51%
after two retries; the victim fails 55% in the suite and never alone, the hidden dependant 51% in the suite and
always alone; Google's 1.5% of runs and 16% of tests. Bisection finds the polluter among 159 tests in 7 runs.
Fuzzing the assembler: of 20,000 random programs, 7,292 crash at 24 sites instead of raising
AsmError. - 6. Testing the tests. Mutation testing; the assembler's tests cover 77% of its statements and kill 62% of 146
mutants; 10 survivors sit on lines the tests run (
.wordreserving 5 bytes;jandretoverwritingra); Google's mutation analysis in review. Statement, branch, MC/DC and exhaustive coverage. - 7. Changing code that works. Refactoring, characterization tests, smells. A model of technical debt over two years: never refactoring delivers 565, 10% 790, 20% 832, 30% 728. The 100× cost-of-delay curve against Menzies et al.'s 171 projects; Bossavit's leprechauns.
- 8. Review and process. Inspections and modern review; review size. Royce's waterfall, iterations, the Agile Manifesto. Integration interval against merge conflicts (daily: 35% of merges, 3 conflicts per week of work; every two weeks: 99%, 15 per week). WIP limits: no limit, 1,309 items in progress and 840 days each; a limit of 8, 6.3 days; Little's law. DORA's four metrics; Goodhart.
- 9. Teams. Conway's law and the inverse manoeuvre; Windows Vista's organizational metrics. n(n − 1)/2. Brooks' law simulated: four people added in month 2 finish in month 17.8, in month 16 in 22.6 against 22.3 with nobody added; from the start, 24 people is fastest. The truck factor; xz.
- 10. Estimates. Lognormal tasks: median 5 days, mean 6. Twenty tasks: plan 100 days; on time 27%, 12%, 4% for σ = 0.3, 0.6, 1.0; four parallel streams 1%. The cone of uncertainty; reference-class forecasting.
- 11. The profession. Licenses from MIT to AGPL; open-source economics and Heartbleed. The Post Office Horizon scandal and the 737 MAX. Privacy by design, accessibility, Therac-25, the ACM Code.
- 12. Frontier: evidence, and machines that code. Mining repositories; code is natural (a trigram model: 4.3 bits per token on this repository's code, 8.0 on the novels). HumanEval's pass@k and SWE-bench; tests as an incomplete oracle, shown by our assembler's surviving mutants. Four open problems, and the ★ research problem.
- Outro. Recap, payoffs, practice, problems, next part.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
-
Hook: the 1968 NATO conference; OS/360 and Brooks' law (adding people to a late project makes it later).
-
Complexity, essential and accidental ("No Silver Bullet", 1986). Parnas 1972: the KWIC system decomposed two ways, and one change rippling through one decomposition but not the other.
-
Abstraction:
- abstract data types (Liskov & Zilles 1974);
- representation invariants and abstraction functions;
- design by contract (Meyer);
- behavioural subtyping (Liskov & Wing 1994).
-
Coupling and cohesion, measured on this repository's own import graph: cycles, layering, dependency inversion, instability and abstractness metrics.
-
Object-oriented design: encapsulation, polymorphism (vtables, callback to Part 15), composition over inheritance; SOLID stated precisely, each with a counterexample.
-
Design patterns (Gamma et al. 1994) as reusable shapes:
- strategy, observer, visitor, adapter, decorator, factory;
- the expression problem (Wadler 1998);
- their functional equivalents; anti-patterns.
-
Functional design in industry: immutability; a pure core inside an imperative shell; making illegal states unrepresentable with algebraic data types (callback to Part 14).
-
Testing in practice:
- the test pyramid; unit, integration and end-to-end tests;
- test doubles (fakes, stubs, mocks);
- flaky tests and their causes (order, time, concurrency; Google's statistics, cited);
- coverage and its limits; mutation score.
-
Refactoring (Opdyke 1992; Fowler): behaviour-preserving transformations; code smells; characterization tests for legacy code (Feathers).
-
Technical debt (Cunningham 1992) as a debt with interest. The cost-of-a-defect curve, and how weakly the classic 100× figure is supported (Menzies et al. 2016, cited).
-
Code review: what it catches (Bacchelli & Bird 2013); review size against detection; linters and static analysis in CI (Part 54).
-
Process:
- waterfall (Royce 1970, who argued against it), iterative development, agile, Scrum and Kanban;
- work in progress as a queue (Little's law again, callback to Part 31);
- the DORA metrics (Accelerate).
-
Conway's law (1968) and the inverse Conway manoeuvre; Brooks' law with n(n − 1)/2 communication channels and a ramp-up model (simulated).
-
Estimation: the planning fallacy; heavy-tailed (lognormal) task durations; a Monte Carlo schedule with its tail; the cone of uncertainty.
-
The profession:
- permissive against copyleft licenses;
- the economics of open source;
- privacy by design (data minimization, purpose limitation);
- accessibility obligations; the ACM Code of Ethics.
Outro.
Computed: this repository's import graph with its cycles and layering metrics; flakiness of an order-dependent test suite; a Brooks' law simulation; Monte Carlo schedules; mutation testing of a Pebble toolchain module. Visuals: the two KWIC decompositions with a change rippling through one; dependency graphs with cycles lit; the communication graph's edges growing quadratically as people join; a schedule distribution and its tail. In practice: how industry codebases are structured, reviewed and tested; the vocabulary of design docs and design reviews; working on a team. Reading: Brooks, The Mythical Man-Month (with "No Silver Bullet"); Ousterhout, A Philosophy of Software Design; McConnell, Code Complete; Hunt & Thomas, The Pragmatic Programmer; Gamma, Helm, Johnson & Vlissides, Design Patterns; Fowler, Refactoring; Feathers, Working Effectively with Legacy Code; Liskov & Guttag, Program Development in Java; Meyer, Object-Oriented Software Construction; Winters, Manshreck & Wright, Software Engineering at Google; Forsgren, Humble & Kim, Accelerate; Naur & Randell 1969; Parnas 1972; Conway 1968; Liskov & Wing 1994.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
Parnas 的模块。 对第二种分解,列出每个模块隐藏的设计决策,并预测四项改动各自会触及哪些模块。
解答
行存储隐藏词与行的表示方式;输入模块隐藏输入格式;循环移位器隐藏移位的表示;排序器隐藏何时以及如何排序;输出模块 隐藏输出格式;主控隐藏调用顺序。把词压缩存储是行存储的决策,输入格式是输入模块的决策,完整存储移位是移位器的决策,按需排序是 排序器的决策:各只触及一个模块,与测量一致。在流程图式设计中,词表和移位列表是共享的,读取它们的每个模块都知道表示方式: 分别触及 3、1、3、2 个模块。
-
行为子类型。 写出前置条件与后置条件的规则,并说明更强的前置条件会破坏调用方。
解答
当 pre_T ⇒ pre_S(子类型至少接受父类型接受的)且 post_S ⇒ post_T(它的承诺至少同样多)时,S 的方法 m 才是 T 的 合法覆盖。设 T.withdraw 要求 0 < a ≤ 余额,而 S.withdraw 要求 0 < a ≤ 余额 − 100。一个对 T 证明正确的调用方对 S 对象调用 withdraw(余额):T 的前置条件成立,S 的不成立,调用出错,所以用 S 替换破坏了一个正确的调用方。
-
Little 定律。 对开始和结束时都为空的系统证明 L = λW。
解答
设 N(t) 为 [0, T] 内系统中的数目,第 i 件在系统内停留 W_i。面积 A = ∫ N(t) dt 按竖直方向计数,等于各件停留时间之和, A = Σ W_i。于是 A/T = (n/T)(Σ W_i / n),即 L = λW,其中 L = A/T 是平均在制数,λ = n/T 是吞吐量,W 是平均停留时间。在看板 表中,限额为 8 时在制 5.37 件、每天完成 0.796 件,由定律得 W = 6.7 天,测得 6.3 天(差别来自测量剔除的预热期)。
-
并行的工作流。 对 k 条相互独立的工作流,证明 P(按时) = ∏ P(第 i 条按时)。
解答
项目按时当且仅当每条工作流都按时:{max_i T_i ≤ D} = ∩_i {T_i ≤ D},独立事件交的概率等于乘积。我们四条工作流各有 五项任务、计划 25 天;单条按时的概率 p ≈ 0.31,四条都按时为 p⁴ ≈ 0.009,与模拟的 1% 一致。
-
动手。 杀死测试已执行到的那些行上存活的十个变异体。
解答
解答要点。 对
.word:汇编.word 1, 2后接一个标号,断言该标号地址为 8。对j和ret:先把ra设为已知值,执行j(以及一次call后接ret),再断言ra的值。对x + 4这类常量表达式:汇编la a0, x+4并检查立即数。重新运行变异 工具后,应只剩下未执行行上的变异体;它们需要针对错误路径的测试(也会暴露模糊测试发现的崩溃:这些行抛出IndexError而不是AsmError)。 -
★ 研究。 设计一个测试充分性评分,能预测被测试接受的补丁是否真正正确。
讨论。 尚未解决。变异得分衡量测试集拒绝原程序附近错误程序的能力,而这正是补丁所处的分布;覆盖率不能衡量这一点。一个研究 方案:生成正确性已知的补丁(变异体,以及修复后程序的变异体),测量每个测试集接受错误补丁的频率,并检验变异得分或其加权版本 (按变异类型或与补丁的距离加权)能否预测真实错误补丁被接受的情况,例如在 SWE-bench 任务上。
Build the film
python -m videos.cs.cs40.compute # the part's numbers, into .cache/cs40
python tools/build.py cs40 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs40 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs40. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs40.compute
python -m unittest tests.test_cs40_se
python tools/build.py cs40