Lecture 34 (Sherriff) - Speed, Simplicity, Correctness

Lecture Date: Wednesday, April 8

Do you remember Lab 2? The one with the robot and counting rooms? We’re going to circle back around to that today.

What makes code “good”? It’s kind of an arbitrary question. Code can always be “better” to some degree.

It could be:

  • faster
  • easier to read
  • have fewer bugs

We can almost always improve on one of these three areas: speed, simplicity, and correctness. All of them don’t have to be perfect to have a “working” system. (Yes, even correctness - most, if not all, software ships with some known errors in it.)

Consider these two bits of code:

1
2
3
4
5
6
int x = a;
int y = b;
// swap x and y:
int tmp = x; // x = a, y = b, tmp = a
x = y;       // x = b, y = b, tmp = a
y = tmp;     // x = b, y = a, tmp = a
1
2
3
4
5
6
int x = a;
int y = b;
// swap x and y:
x -= y;    // x = a-b,         y = b
y += x;    // x = a-b,         y = b+(a-b) = a
x = y - x; // x = a-(a-b) = b, y = a

Which is “better”? Why?

Today we start on discussing various core algorithms in CS. We want to write “good code” that’s “fast” and “easy to maintain.” So what exactly does that mean?

As an example, we’ll play with a robot counting rooms, just like you did in Lab 2.