Tutorial outline

Unit 1

  1. 01Getting started
  2. 02Names and functions
  3. 03Control
  4. 04Higher-order functions
  5. 05Environments and closures
  6. 06Functional abstraction
  7. 07Recursion
  8. 08Tree recursion
  1. D0Getting started
  2. D1Control and environment diagrams
  3. HW1Functions and control
  4. D2Higher-order functions
  5. HW2Higher-order functions
  6. P1Hog
  7. D3Recursion
  8. D4Tree recursion
  9. HW3Recursion

Unit 2

  1. 09Sequences
  2. 10Dictionaries, sets, and tuples
  3. 11Optionals
  4. 12Structures and enumerations
  5. 13Linked lists and trees
  6. 14Mutation and value semantics
  7. 15Classes and inheritance
  8. 16Protocols and generics
  9. 17Iterators and lazy sequences
  10. 18Efficiency and memoization
  1. HW4Sequences and containers
  2. P2Cats
  3. D5Trees
  4. HW5Recursive data and mutation
  5. D6Objects and classes
  6. HW6Classes and interfaces
  7. P3Ants vs. SomeBees
  8. D7Iterators and efficiency
  9. HW7Lazy sequences and efficiency

Unit 3

  1. 19Algebraic data types and pattern matching
  2. 20Writing an interpreter
  3. 21Error handling
  4. 22Concurrency with async and await
  5. 23Testing
  6. 24Building a Swift package
  1. D8Algebraic data types
  2. HW8Pattern matching
  3. D9Interpreters
  4. HW9Interpreters and errors
  5. P4Scheme
  6. D10Concurrency
  7. D11Testing
  8. HW10Concurrency and testing

Unit 4

  1. 25References, identity, and memory
  2. 26Drawing with SwiftUI
  3. 27Testing data structures
  4. 28IntLists and SLLists
  5. 29Doubly linked lists and deques
  6. 30Arrays from scratch
  7. 31Interface and implementation inheritance
  8. 32Iteration, equality, and ordering
  9. 33Copy-on-write collections
  1. D12Swift review
  2. D13References, classes, and arrays
  3. HW11Swift warm-up
  4. P5Particle Simulator
  5. D14IntLists and SLLists
  6. HW12IntLists
  7. P6LinkedListDeque
  8. D15DLLists, default implementations, and array lists
  9. P7ArrayDeque
  10. D16Comparables and iterators
  11. HW13Review I

Unit 5

  1. 34Asymptotic analysis
  2. 35Disjoint sets
  3. 36Analyzing recursion
  4. 37Amortized analysis and the limits of big O
  5. 38Sets, maps, and binary search trees
  6. 39B-trees
  7. 40Left-leaning red-black trees
  8. 41Heaps and priority queues
  1. D17Asymptotics and disjoint sets
  2. P8Percolation
  3. D18Asymptotics II
  4. HW14Asymptotic analysis
  5. D19BSTs, B-trees, and LLRBs
  6. HW15BSTMap

Unit 6

  1. 42Data-driven apps with SwiftUI
  2. 43Tree and graph traversals
  3. 44Graph implementations
  4. 45Shortest paths: Dijkstra and A*
  5. 46Minimum spanning trees
  6. 47DAGs, topological sort, and reductions
  1. D20Tree traversals and graphs
  2. P9NGordNet
  3. D21Shortest paths and MSTs

Unit 7

  1. 48Hash tables
  2. 49Hash functions
  3. 50Tries and prefix operations
  4. 51Software engineering: managing complexity
  5. 52Games with SwiftUI
  6. 53Designing a world
  7. 54Basic sorts
  8. 55Quicksort and selection
  9. 56The limits of sorting
  10. 57Radix sorts
  11. 58Compression and complexity
  12. 59Computing, society, and what comes next
  1. D22Hashing and tries
  2. HW16Review II
  3. D23Hashing and tries, revisited
  4. P10Build Your Own World
  5. D24Sorting
  6. HW17HashMap
  7. D25Sorting II
  8. HW18LLRB set
  9. HW19Final review

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

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 20 in 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!)

Type Error if running it would crash. For several lines of output, put each on its own line.

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 of list.remove(at: 3) needs no documentation.
  • Omit words that repeat type information: allViews.remove(cancelButton), not removeElement.
  • Name mutating and nonmutating pairs consistently: sort() and sorted(), append(_:) and appending(_:).
  • 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.

  1. }
  2. mutating func push(_ x: Int) { items.append(x) }
  3. var stack = Stack()
  4. for x in 1...3 { stack.push(x) }
  5. struct Stack {
  6. print(stack.count)
  7. private var items: [Int] = []
  8. 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(""))

Type Error if running it would crash. For several lines of output, put each on its own line.

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: Bool
  • doStuff says nothing; removingDuplicates says what, and the -ing form says it returns a new value instead of changing its input.
  • get, The, and String add no information; for makes the call read as a phrase: userName(for: 42).
  • sort() and sorted() 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.