6.102 - Software Construction - Halfway done, my thoughts and summaries
So far, I like this course. My pace has been pretty slow though. I went up to 09: Equality. 2nd half will be 10: Functional Programming and the rest.
I reviewed some git version control and typescript basics. The typescript basics included mutating vs. reassigning, arrays/maps/sets, variable declarations, objects, enumerations, APIs, and programming toolbox.
The readings were interesting. The main themes were to make software safe from bugs, ready for change, and easy to understand. Will be putting the objectives and summaries here, so that I can have it in one place if I decided to revisit/review. Here are my thoughts on each reading:
Reading 1: Static Checking
Two main topics in this reading. Static typing and the big three properties of good software. Went over some basics of types and static typing. Static typing prevents a large class of bugs from infecting programs. So, TypeScript is a statically typed language, which compiles into JavaScript, a dynamically typed language.
Interesting design choice by JavaScript’s designers was to do no checking for many dynamic cases. For example, when a string or array index is out of bounds, or a key is not found in a map, JavaScript returns the special value undefined, rather than throwing an error as Python would. No checking makes bugs harder to find than they might otherwise be, because the special values can propagate through further computations until a failure finally occurs much farther away from the original mistake in the code.
Another trap in typescript — which is shared by many other programming languages — is that its numeric type has corner cases that do not behave like the integers and real numbers we’re used to. As a result, some errors that really should be dynamically checked are not checked at all. The traps include limited precision for integers, special values, and overflow/underflow.
Here we get introduced to mutability and reassignment. The reading says that good programmers try to avoid things that change, because they may change unexpectedly. Immutability is a major design principle in this course.
I learned that TypeScript doesn’t have immutable tuples like Python does, but it does have ReadonlyArray, which is an array type that omits the mutator operations.
Using const to prevent reassignment may be a good practice in TypeScript, it appears.
I learned that it is a good idea to document assumptions.
Hacking vs. engineering. Hacking is often marked by unbridled optimism. But software engineering is not hacking. Engineers are pessimists.
Bad: writing lots of code before testing any of it; keeping all the details in your head, assuming you (and everyone using your code) will remember them forever, instead of writing them down in your code; assuming that bugs will be nonexistent or else easy to find and fix.
Good: write a little bit at a time, testing as you go. In a future reading, test-first programming is discussed; document the assumptions that your code depends on; defend your code against stupidity — especially your own ! Static checking helps with that.
The Goals of 6.102:
Our primary goal in this course is learning how to produce software that is:
- Safe from bugs. Correctness (correct behavior right now) and defensiveness (correct behavior in the future) are required in any software we build.
- Easy to understand. The code has to communicate to future programmers who need to understand it and make changes in it (fixing bugs or adding new features). That future programmer might be you, months or years from now. You’ll be surprised how much you forget if you don’t write it down, and how much it helps your own future self to have a good design.
- Ready for change. Software always changes. Some designs make it easy to make changes; others require throwing away and rewriting a lot of code.
There are other important properties of software (like performance, usability, security), and they may trade off against these three. But these are the Big Three that we care about in 6.102, and that software developers generally put foremost in the practice of building software. It’s worth considering every language feature, every programming practice, every design pattern that we study in this course, and understanding how they relate to the Big Three.
They give reasons for why we use TypeScript in this course. Basically, it’s a reasonable choice of language right now to learn how to write code that it safe from bugs, easy to understand, and ready for change.
The real skills gained from this course are not language-specific, but carry over to any language that you might program in. The most important lessons from this course will survive language fads: safety, clarity, abstraction, engineering instincts.
Summary The main idea we introduced today is static checking. Here’s how this idea relates to the goals of the course:
- Safe from bugs. Static checking helps with safety by catching type errors and other bugs before runtime.
- Easy to understand. It helps with understanding, because types are explicitly stated in the code.
- Ready for change. Static checking makes it easier to change your code by identifying other places that need to change in tandem.
Reading 2: Testing
Objectives After this reading, you should:
- understand the value of testing, and know the process of test-first programming;
- be able to judge a test suite for correctness, thoroughness, and size;
- be able to design a test suite for a function by partitioning its input space and choosing good test cases;
- be able to judge a test suite by measuring its code coverage; and
- understand and know when to use black box vs. glass box testing, unit tests vs. integration tests, and automated regression testing.
Can’t say I remember all of this perfectly now that I’m reviewing. I think I chunked some of the important concepts though.
Software testing is hard. There are quite a few reasons why which I won’t get into right now. The reading taught me to choose test cases carefully and systematically. This reading goes over some techniques for systematic testing.
Went over some terms such as module, specification, implementation, clients, test case, and test suite.
And here we are introduced to our first programming recipe in this course !
The development of a single function proceeds in this order:
- Spec: write a specification for the function — describe the behavior, parameter types, constraints, etc.
- Test: write tests that exercise the specification
- Implement: Write the implementation
Once your implementation passes the tests you wrote, you’re done. Don’t leave testing until the end of development, when you have a bunch of unvalidated code. I will now test my code as I develop it.
The reading then taught me some testing techniques, including choosing test cases by partitioning, automated unit testing, documenting your testing strategy, black box and glass box testing, coverage, unit and integration testing, automated regression testing, iterative test-first programming, and randomized testing.
There were quite a few useful nuggets of knowledge here. Definitely changed the way I think about testing programs. It can be quite involved and require a good amount of thought. But can be simplified in some cases.
Summary In this reading, we saw these ideas:
- Test-first programming. Write tests before you write code.
- Systematic testing with partitioning and boundary values, to design a test suite that is correct, thorough, and small.
- Glass box testing and statement coverage for filling out a test suite.
- Unit-testing each module, in isolation as much as possible.
- Automated regression testing to keep bugs from coming back.
- Iterative development. Plan to redo some work.
The topics of today’s reading connect to our three key properties of good software as follows:
- Safe from bugs. Testing is about finding bugs in your code, and test-first programming is about finding them as early as possible, right after you introduce them.
- Easy to understand. Systematic testing with a documented testing strategy makes it easier to understand how test cases were chosen and how thorough a test suite is.
- Ready for change. Correct test suites only depend on behavior in the spec, which allows the implementation to change within the confines of the spec. We also talked about automated regression testing, which helps keep bugs from coming back when changes are made to code.
Reading 3: Code Review
Here I learned some general tips for code review. Here is a summary:
Summary Code review is a widely-used technique for improving software quality by human inspection. Code review can detect many kinds of problems in code, but as a starter, this reading talked about these general practices for good code:
- Don’t Repeat Yourself (DRY)
- Comment where needed
- Fail fast
- Avoid magic numbers
- One purpose for each variable
- Use good names
- Use whitespace and punctuation to help the reader
- Don’t use global variables
- Functions should return results, not print them
- Avoid special-case code
- Code at the right length The topics of today’s reading connect to our three key properties of good software as follows:
- Safe from bugs. In general, code review uses human reviewers to find bugs. DRY code lets you fix a bug in only one place, without fear that it has propagated elsewhere. Documenting your assumptions with clear comments makes it less likely that another programmer will introduce a bug. The Fail Fast principle detects bugs as early as possible. Avoiding global variables makes it easier to localize bugs related to variable values, since non-global variables can be changed in only limited places in the code.
- Easy to understand. Code review is really the only way to find obscure or confusing code, because other people are reading it and trying to understand it. Using judicious comments, avoiding magic numbers, keeping one purpose for each variable, using good names, and using whitespace well can all improve the understandability of code.
- Ready for change. Code review helps here when it’s done by experienced software developers who can anticipate what might change and suggest ways to guard against it. DRY code is more ready for change, because a change only needs to be made in one place. Returning results instead of printing them makes it easier to adapt the code to a new purpose.
Code review is not the only software development practice with strong supporting evidence. Another is: sleep.
Reading 4: Specifications
Objectives
- Understand preconditions and postconditions in function specifications, and be able to write correct specifications
- Be able to write tests against a specification
- Understand how to use exceptions
It’s interesting how technical this course gets when it comes to writing specifications. Specifications are the “linchpin of teamwork.” The specification acts as a contract: the implementer is responsible for meeting the contract, and a client that uses the function can rely on the contract.
Why specifications? They can help make a program both ready for change and safe from bugs. I like the way they broken down the structure of a specification.
Summary
A specification acts as a crucial firewall between the implementer of a module and its client. It makes separate development possible: the client is free to write code that uses the module without seeing its source code, and the implementer is free to write the code that implements the module without knowing how it will be used. Let’s review how specifications help with the main goals of this course:
- Safe from bugs. A good specification clearly documents the mutual assumptions that a client and implementer rely on. Bugs often come from disagreements at the interfaces, and the presence of a specification helps avoid those disagreements. Using machine-checked language features in your spec, like static typing and exceptions rather than just a human-readable comment, can reduce bugs still more.
- Easy to understand. A short, simple spec is easier to understand than the implementation itself, and saves other people from having to read the code.
- Ready for change. Specs establish contracts between different parts of your code, allowing those parts to change independently as long as they continue to satisfy the requirements of the contract.
Reading 5: Designing Specifications
Objectives
- Understand underdetermined specs, and be able to identify and assess specs that are not deterministic
- Understand declarative vs. operational specs, and be able to write declarative specs
- Understand strength of preconditions, postconditions, and specs, and be able to compare spec strength
- Be able to write coherent, useful specifications of appropriate strength
It was a lengthy reading. I liked the section on mutability in particular, because it demonstrated some potential bugs and how to avoid them. Favor immutability whenever possible.
Summary
A specification acts as a crucial firewall between implementor and client — both between people (or the same person at different times) and between code. As we saw last time, it makes separate development possible: the client is free to write code that uses a module without seeing its source code, and the implementor is free to write the implementation code without knowing how it will be used.
Declarative specifications are the most useful in practice. Preconditions (which weaken the specification) make life harder for the client, but applied judiciously they are a vital tool in the software designer’s repertoire, allowing the implementor to make necessary assumptions. As always, our goal is to design specifications that make our software:
- Safe from bugs. Without specifications, even the tiniest change to any part of our program could be the tipped domino that knocks the whole thing over. Well-structured, coherent specifications minimize misunderstandings and maximize our ability to write correct code with the help of static checking, careful reasoning, testing, and code review.
- Easy to understand. A well-written declarative specification means the client doesn’t have to read or understand the code. You’ve probably never read the code for, say, Python dict.update, and doing so isn’t nearly as useful to the Python programmer as reading the declarative spec.
- Ready for change. An appropriately weak specification gives freedom to the implementor, and an appropriately strong specification gives freedom to the client. We can even change the specs themselves, without having to revisit every place they’re used, as long as we’re only strengthening them: weakening preconditions and strengthening postconditions.
As I’m reviewing this, I realize that doing the assignments and projects in this course would help to ingrain these concepts. Unfortunately, I don’t have access to these. So, I suppose I’ll have to hope that I’m chunking the information as I’m reading and building understanding, so that if it is needed, I’ll at least know where to look, if not have an idea of how to apply the concept.
Reading 6: Abstract Data Types
Objectives Today’s class introduces two ideas:
- Abstract data types
- Representation independence
Lots of good stuff here with plenty of reading exercises.
Summary
- Abstract data types are characterized by their operations.
- Operations can be classified into creators, producers, observers, and mutators.
- An ADT’s specification is its set of operations and their specs.
- A good ADT is simple, coherent, adequate, and representation independent.
- An ADT is tested by generating tests for each of its operations, but using the creators, producers, mutators, and observers together in the same tests.
These ideas connect to our three key properties of good software as follows:
- Safe from bugs. A good ADT offers a well-defined contract for a data type, so that clients know what to expect from the data type, and implementers have well-defined freedom to vary.
- Easy to understand. A good ADT hides its implementation behind a set of simple operations, so that programmers using the ADT only need to understand the operations, not the details of the implementation.
- Ready for change. Representation independence allows the implementation of an abstract data type to change without requiring changes from its clients.
Reading 7: Abstraction Functions and Rep Invariants
Objectives Today’s reading introduces several ideas:
- invariants
- representation exposure
- abstraction functions
- representation invariants
In this reading, we study a more formal mathematical idea of what it means for a class to implement an ADT via the notions of abstraction functions and rep invariants. These mathematical notions are eminently practical in software design. The abstraction function gives us a way to cleanly define the equality operation on an abstract data type (which we’ll discuss in more depth in a future class). The rep invariant makes it easier to catch bugs caused by a corrupted data structure.
It was a nice, technical reading. I was happy to see that they included some Recipes for Programming ! Going to copy them here, for easy access:
Recipes for programming
Abstract data types are at the heart of software construction for correctness, clarity, and changeability. Recall the test-first programming approach for: Writing a method
- Spec. Write the spec, including the method signature (name, argument types, return types, exceptions), and the precondition and the postcondition as a documentation comment.
- Test. Create systematic test cases and put them in test file so you can run them automatically.
- You may have to go back and change your spec when you start to write test cases. Just the process of writing test cases puts pressure on your spec, because you’re thinking about how a client would call the method. So steps 1 and 2 iterate until you’ve got a better spec and some good test cases.
- Make sure at least some of your tests are failing at first. A test suite that passes all tests even when you haven’t implemented the method is not a good test suite for finding bugs.
- Implement. Write the body of the method. You’re done when the tests are all passing.
- Implementing the method puts pressure on both the tests and the specs, and you may find bugs that you have to go back and fix. So finishing the method may require changing the implementation, the tests, and the specs, and bouncing back and forth among them.
Let’s broaden this to a recipe for: Writing an abstract data type
- Spec. Write specs for the operations of the data type, including method signatures, preconditions, and postconditions.
- This includes defining the abstract value space, but not the abstraction function (since we don’t have a rep yet).
- Test. Write test cases for the ADT’s operations.
- Again, this puts pressure on the spec. You may discover that you need operations you hadn’t anticipated, so you’ll have to add them to the spec.
- Implement. For an ADT, this part expands to:
- Choose rep. Write down the private fields of a class (or, as we’ll see in future readings, choose and define a different kind of rep). Write down the rep invariant and abstraction function as a comment.
- Assert rep invariant. Implement a checkRep() method that enforces the rep invariant. This is critically important if the rep invariant is nontrivial, because it will catch bugs much earlier.
- Implement operations. Write the method bodies of the operations, making sure to call checkRep() in them. You’re done when the tests are all passing.
And let’s broaden it further to a recipe for: Writing a program (consisting of ADTs and functions)
- Choose data types. Decide which ones will be mutable and which immutable.
- Choose functions. Write your top-level main function and break it down into smaller steps.
- Spec. Spec out the ADTs and functions. Keep the ADT operations simple and few at first. Only add complex operations as you need them.
- Test. Write test cases for each unit (ADT or function).
- Implement simply first. Choose simple, brute-force representations. The point here is to put pressure on the specs and the tests, and try to pull your whole program together as soon as possible. Make the whole program work correctly first. Skip the advanced features for now. Skip performance optimization. Skip corner cases. Keep a to-do list of what you have to revisit.
- Iterate. Now that it’s all working, make it work better. Reimplement, optimize, redesign if necessary
I might be coming back to these recipes to help write future programs.
Summary
- An invariant is a property that is always true of an ADT object instance, for the lifetime of the object.
- A good ADT preserves its own invariants. Invariants must be established by creators and producers, and preserved by observers and mutators.
- The rep invariant specifies legal values of the representation, and should be checked at runtime with checkRep().
- The abstraction function maps a concrete representation to the abstract value it represents.
- The rep of an immutable ADT may change, as long as the abstract value it represents doesn’t change.
- Representation exposure threatens both representation independence and invariant preservation.
- An invariant should be documented, by comments or even better by assertions like checkRep(), otherwise the invariant is not safe from bugs.
The topics of today’s reading connect to our three properties of good software as follows:
- Safe from bugs. A good ADT preserves its own invariants, so that those invariants are less vulnerable to bugs in the ADT’s clients, and violations of the invariants can be more easily isolated within the implementation of the ADT itself. Stating the rep invariant explicitly, and checking it at runtime with checkRep(), catches misunderstandings and bugs earlier, rather than continuing on with a corrupt data structure.
- Easy to understand. Rep invariants and abstraction functions explicate the meaning of a data type’s representation, and how it relates to its abstraction.
- Ready for change. Abstract data types separate the abstraction from the concrete representation, which makes it possible to change the representation without having to change client code.
Reading 8: Defining ADTs with Interfaces, Generics, Enums, and Functions
Objectives Today’s class is about various ways to implement abstract data types, including:
- interfaces: separating the interface of an ADT from its implementation;
- generic types: defining a family of ADTs using generic type parameters;
- enumerations: defining an ADT with a small finite set of values;
- global functions operating on an opaque type: rare in TypeScript but common in non-object-oriented languages.
We also discuss subtyping as a relationship between two types determined by their specs, and distinguish it from subclassing, which involves reps as well. After today’s class, you should be able to:
- define ADTs using classes, interfaces, generics, and enumerations
- determine whether one type is a subtype of another
Lots of examples in this reading and rationale for why to use things.
Summary TypeScript interfaces help us formalize the idea of an abstract data type as a set of operations that must be supported by a type. This helps make our code…
- Safe from bugs. An ADT is defined by its operations, and interfaces do just that. When clients use an interface type, static checking ensures that they only use methods defined by the interface. If the implementation class exposes other methods — or worse, has visible representation — the client can’t accidentally see or depend on them. When we have multiple implementations of a data type, interfaces provide static checking of the method signatures.
- Easy to understand. Clients and maintainers know exactly where to look for the specification of the ADT. Since the interface doesn’t contain fields or implementations of instance methods, it’s easier to keep details of the implementation out of the specifications.
- Ready for change. We can easily add new implementations of a type by adding classes that implement an interface. If we avoid constructors in favor of factory functions, clients will only see the interface. That means we can switch which implementation class clients are using without changing their code at all.
TypeScript enumerations allow defining an ADT with a small finite set of immutable values. Compared to the old-fashioned alternatives of special integer values or special strings, enumerations help make our code:
- Safe from bugs. Static checking ensures that clients can’t use values outside the finite set, or confuse two different enumerated types.
- Easy to understand. Named constants are not as magical as integer literals, and named types explain themselves better than number or string.
- Ready for change. The code that uses a particular enumeration is easy to find by searching for the enumeration’s type name, so that it can be reviewed and changed when the enumeration changes. (IDE refactoring tools can even do some of these changes automatically.) Code that depends on a particular set of string or integer constants is much harder to distinguish from code that uses strings and integers for other purposes.
Reading 9: Equality
Objectives
- Understand the properties of an equivalence relation.
- Understand equality for immutable types defined in terms of the abstraction function and in terms of observation.
- Differentiate between reference equality and object equality.
- Differentiate between observational and behavioral equality for mutable types.
All about equality. Great reading. Here’s the summary:
Summary
- Equality should be an equivalence relation (reflexive, symmetric, transitive).
- The abstraction function is the basis for equality in immutable data types.
- Mutable data types have two useful notions of equality: behavioral equality (which provides consistent equality over time) and observational equality (which uses the abstraction function). For immutable types, observational and behavioral equality are identical.
In TypeScript, for immutable built-in types (e.g. number, string, bigint):
- Use === for behavioral and observational equality, which are identical because there are no mutators.
- Avoid == because of its automatic conversions.
- Safe for use as Set elements and Map keys.
For immutable object types (e.g. Duration):
- Use equalValue() for both behavioral and observational equality, which are identical because there are no mutators.
- Avoid === because it is too strong, and avoid == because of its automatic conversions.
- Not safe for use as Set elements or Map keys because those data structures compare objects using ===.
For mutable object types:
- Use === for behavioral equality.
- Use equalValue() for observational equality.
- Avoid == because of its automatic conversions.
- Safe for use as Set elements and Map keys.
Equality is one part of implementing an abstract data type, and we’ve already seen how important ADTs are to achieving our three primary objectives. Let’s look at equality in particular:
- Safe from bugs. Correct implementation of equality is essential for clients of a data type, and also highly desirable for writing tests.
- Easy to understand. Clients and other programmers who read our specs will expect our types to implement an appropriate equality operation, and will be surprised and confused if we do not.
- Ready for change. Correctly-implemented equality for immutable types separates equality of reference from equality of abstract value, hiding from clients our decisions about whether values are shared.
Now I have to be thinking about equality when it comes to mutable and immutable types. I can refer to this reading whenever I need guidance.
That’s it for all the readings I’ve read so far ! This was a good review. Next reading is Functional Programming. When I complete the course, I write the 2nd half blog post.