Software engineering: managing complexity
Why large programs become hard to change: complexity and its symptoms, dependencies and obscurity, deep modules with simple interfaces, information hiding and leakage, tactical versus strategic programming, and naming and comments in Swift.
- CS61B
- Software Engineering I · Textbook Ch. 27
- Swift book
- Access Control
- Documentation
- API Design Guidelines
Every program in this course has been small enough to hold in your head. Project 10 is not, and real software is far larger: millions of lines, written over years by people who never meet. CS61B’s software engineering lectures, the first given by John Ousterhout, ask what makes such programs hard to work on, and what to do about it. This lesson follows his answer, from A Philosophy of Software Design, with Swift examples.
Complexity
Ousterhout defines complexity as anything about a program’s structure that makes it hard to understand or change. It shows up in three ways:
- Change amplification: a simple change needs edits in many places. If the
maximum length of a username is written as
20in eleven files, changing it is eleven edits, and missing one is a bug. - Cognitive load: how much you must know to make a change safely. A function that works only if two other functions were called first, in the right order, puts that knowledge on every caller.
- Unknown unknowns: it is not obvious what you need to know, or which code a change affects. This is the worst, because you cannot even tell you are missing something.
Complexity has two causes. Dependencies: a piece of code cannot be understood or changed alone, because it relies on others. Obscurity: important information is not obvious, such as a variable name that does not say what it holds, or a rule that is written nowhere.
Complexity is incremental. No single shortcut makes a program unmanageable; thousands of them do. That is why it has to be resisted continuously, not fixed later.
Deep modules
A module is any unit with an interface and an implementation: a function, a type, a package. Its cost to everyone else is its interface, what users must know. Its benefit is its functionality, what it does for them. The best modules are deep: a small, simple interface over a lot of functionality.
Swift’s Dictionary is deep: dict[key] hides hashing, collision handling,
resizing, and copy-on-write, everything in Lessons 33, 48, and 49. Lesson 29’s
deque was deep too: callers of addFirst never saw nodes, sentinels, or weak
links.
A shallow module has an interface nearly as complicated as what it does:
// Shallow: the caller must manage what the type should.
struct ShallowCounter {
var counts: [String: Int] = [:]
func currentCount(for word: String) -> Int? { counts[word] }
mutating func setCount(_ count: Int, for word: String) { counts[word] = count }
}
// Deep: one operation that does the whole job.
struct WordCounter {
private var counts: [String: Int] = [:]
mutating func add(_ text: String) {
for word in text.lowercased().split(whereSeparator: { !$0.isLetter }) {
counts[String(word), default: 0] += 1
}
}
func mostCommon(_ k: Int) -> [(word: String, count: Int)] {
counts.sorted { $0.value != $1.value ? $0.value > $1.value : $0.key < $1.key }
.prefix(k).map { ($0.key, $0.value) }
}
}
var shallow = ShallowCounter()
for word in "The cat saw the dog".split(separator: " ") {
let w = word.lowercased() // every caller repeats this
shallow.setCount((shallow.currentCount(for: w) ?? 0) + 1, for: w)
}
var deep = WordCounter()
deep.add("The cat saw the dog.")
print(shallow.currentCount(for: "the")!, deep.mostCommon(1)[0]) // 2 (word: "the", count: 2)
With the shallow counter, every caller must know to lowercase, to split, and to add one to the old count; a caller who forgets to lowercase gets different counts for “The” and “the”. The deep counter owns those decisions, so they are made once, and correctly.
Information hiding
The main technique for deep modules is information hiding: each module
encapsulates design decisions, such as a data format, an algorithm, or a policy,
so that nothing outside depends on them. Swift’s access control (Lesson 24) is the
tool: private stored properties, and a public surface that describes what,
not how.
The opposite is information leakage: one decision reflected in several
modules. A common form is temporal decomposition, splitting code by the order
things happen instead of by what they know: a FileReader and a FileParser that
both must know the file format. When the format changes, both change. Put
everything that knows the format in one module.
Another warning sign is a type that exposes its internals “for convenience”: a public array inside a sorted collection lets any caller unsort it, and then every method must defend against that.
What would Swift print?
struct SortedList {
private(set) var items: [Int] = []
mutating func insert(_ x: Int) {
let i = items.firstIndex { $0 > x } ?? items.count
items.insert(x, at: i)
}
var smallest: Int? { items.first }
}
var list = SortedList()
for x in [5, 1, 4] { list.insert(x) }
print(list.items, list.smallest!)Show answer and explanation
Answer[1, 4, 5] 1
Because items is private(set), only insert can change it, and insert keeps it
sorted. The invariant “items is sorted” cannot be broken from outside, so
smallest can simply read the first element.
Tactical and strategic programming
Tactical programming aims to get the current feature working as fast as possible, with whatever shortcut works. Each shortcut adds a little complexity. Strategic programming treats working code as not enough: the goal is a good design that also works. It costs a little more now, Ousterhout suggests about 10 to 20 percent of development time, and pays back quickly as the program grows.
In practice, strategic programming means: when you change code, leave its design a little better than you found it; when a change is awkward, ask whether the structure is wrong; and design interfaces for the general case where that costs little, since a somewhat general interface is often simpler than a special-purpose one.
Names and comments
Obscurity is fought with names and comments. Swift’s API Design Guidelines are built around clarity at the point of use: code is read far more often than written, so a call should read well where it appears.
- Name things by what they are for:
remove(at:),firstIndex(of:),mostCommon(_:). A reader oflist.remove(at: 3)needs no documentation. - Omit words that repeat type information:
allViews.remove(cancelButton), notremoveElement. - Name mutating and nonmutating pairs consistently:
sort()andsorted(),append(_:)andappending(_:). - Write a documentation comment (
///) for every declaration that is not obvious, starting with a one-sentence summary.
Comments should say what the code cannot: why a decision was made, what a value means (units, ranges, whether it can be empty), what a caller must know. A comment that repeats the code adds nothing; a missing comment on a subtle invariant is an unknown unknown waiting to happen. The invariant comments you wrote above the stored properties of every project since Project 6 are exactly the comments that matter most.
Put the lines in order
Put the lines in order so the program prints 3.
}mutating func push(_ x: Int) { items.append(x) }var stack = Stack()for x in 1...3 { stack.push(x) }struct Stack {print(stack.count)private var items: [Int] = []var count: Int { items.count }
Show the correct program
struct Stack {
private var items: [Int] = []
mutating func push(_ x: Int) { items.append(x) }
var count: Int { items.count }
}
var stack = Stack()
for x in 1...3 { stack.push(x) }
print(stack.count)Lab 50: Software engineering
Q0: What would Swift print?
What would Swift print?
enum Limits {
static let maxUsernameLength = 20
}
func isValid(_ name: String) -> Bool {
!name.isEmpty && name.count <= Limits.maxUsernameLength
}
print(isValid("ada"), isValid(String(repeating: "a", count: 21)), isValid(""))Show answer and explanation
Answertrue false false
Putting the limit in one named constant removes change amplification: changing it
is one edit. An enum with no cases is a common Swift namespace for constants,
since it cannot be instantiated by accident.
Q1: Deepen a module
This temperature type is shallow: callers must convert units themselves. Redesign it so that it stores one representation privately and offers what callers need: creating from Celsius or Fahrenheit, reading either, and comparing.
struct Temperature {
var value: Double
var isFahrenheit: Bool
}
Show solution
struct Temperature: Comparable {
private let kelvin: Double // one representation, hidden
static func celsius(_ c: Double) -> Temperature { Temperature(kelvin: c + 273.15) }
static func fahrenheit(_ f: Double) -> Temperature { Temperature(kelvin: (f - 32) * 5 / 9 + 273.15) }
var celsius: Double { kelvin - 273.15 }
var fahrenheit: Double { (kelvin - 273.15) * 9 / 5 + 32 }
static func < (a: Temperature, b: Temperature) -> Bool { a.kelvin < b.kelvin }
}
let boiling = Temperature.celsius(100)
assert(abs(boiling.fahrenheit - 212) < 1e-9)
assert(Temperature.fahrenheit(32) < Temperature.celsius(1))
assert(abs(Temperature.fahrenheit(-40).celsius - -40) < 1e-9)The unit is now a decision inside the type. Callers can no longer compare a Celsius
value with a Fahrenheit one by mistake, and if the representation changes, no caller
changes. Static factory methods name the unit at the point of use:
.celsius(100) reads clearly.
Q2: Find the leakage
A program reads a config file with a ConfigReader that returns the raw lines, and a
ConfigParser that splits each line at =. A third type, Settings, looks up values
and also trims spaces around them. Explain the leakage, and redesign it as one deep
module.
Show solution
The format, key = value lines with spaces to trim and perhaps comments, is known by
all three types: temporal decomposition split reading, parsing, and cleanup into
separate modules. Supporting comments would change all three.
struct Config {
private var values: [String: String] = [:]
/// Parses `key = value` lines. Blank lines and lines starting with # are ignored.
init(text: String) {
for line in text.split(separator: "\n") {
let trimmed = line.trimmingPrefix(while: \.isWhitespace)
guard !trimmed.isEmpty, !trimmed.hasPrefix("#"),
let equals = trimmed.firstIndex(of: "=") else { continue }
let key = trimmed[..<equals].filter { !$0.isWhitespace }
let value = trimmed[trimmed.index(after: equals)...].trimmingPrefix(while: \.isWhitespace)
values[String(key)] = String(value)
}
}
subscript(key: String) -> String? { values[key] }
}
let config = Config(text: """
# window
width = 80
title= My World
""")
assert(config["width"] == "80" && config["title"] == "My World" && config["# window"] == nil)Everything that knows the format is in one place, behind a two-member interface.
Q3: Naming
Rename these declarations following the API Design Guidelines, and explain each change.
func doStuff(list: [Int]) -> [Int] // returns the list without duplicates
func getTheUserNameString(id: Int) -> String
mutating func sortList() // sorts in place
func sortListAndReturn() -> [Int] // returns a sorted copy
var flag: Bool // whether the download has finished
Show solution
func removingDuplicates(_ values: [Int]) -> [Int]
func userName(for id: Int) -> String
mutating func sort()
func sorted() -> [Int]
var isFinished: BooldoStuffsays nothing;removingDuplicatessays what, and the-ingform says it returns a new value instead of changing its input.get,The, andStringadd no information;formakes the call read as a phrase:userName(for: 42).sort()andsorted()follow the standard mutating/nonmutating pair, so readers know which is which without looking.- A Boolean property reads as an assertion:
if download.isFinished.
Q4 (optional): Document an invariant
Write documentation comments for a RingBuffer type: a summary, the meaning of each
stored property, the invariant connecting them, and the complexity of each operation.
Then implement it so that the comments are true.
Show solution
/// A first-in, first-out queue with a fixed capacity, stored in a circular array.
///
/// Every operation takes constant time. When the buffer is full, `append`
/// overwrites the oldest item.
struct RingBuffer<Element> {
/// Fixed-size storage. Invariant: the items, oldest first, are at
/// `storage[(start + i) % storage.count]` for `i` in `0..<count`, and every
/// other slot is nil.
private var storage: [Element?]
/// The position of the oldest item.
private var start = 0
/// The number of items, from 0 to `storage.count`.
private(set) var count = 0
init(capacity: Int) {
precondition(capacity > 0)
storage = Array(repeating: nil, count: capacity)
}
/// Adds an item, overwriting the oldest if the buffer is full.
mutating func append(_ item: Element) {
storage[(start + count) % storage.count] = item
if count < storage.count {
count += 1
} else {
start = (start + 1) % storage.count
}
}
/// Removes and returns the oldest item, or nil if empty.
mutating func removeOldest() -> Element? {
guard count > 0 else { return nil }
defer {
storage[start] = nil
start = (start + 1) % storage.count
count -= 1
}
return storage[start]
}
}
var recent = RingBuffer<Int>(capacity: 3)
for n in 1...5 { recent.append(n) }
assert(recent.count == 3 && recent.removeOldest() == 3 && recent.removeOldest() == 4)The invariant comment is the most valuable line in the file: it is exactly what someone changing the type must preserve, and what no amount of reading the methods would make obvious at a glance.
What’s next
Next lesson: SwiftUI for games, keyboard input, a game loop, and saving progress, the last tools Project 10 needs.