Lecture 36 - Speed, Simplicity, Correctness

Lecture Date: Monday, April 18

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:

  • It works (for what set of inputs?) – versatility and correctness
  • It is maintainable – readable, simple, good comments and naming, etc.
  • It is efficient – uses minimal time or memory when running
  • It is easy to create (meaning inexpensive to create too)

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 bits of code:

1
2
3
4
5
6
x = 2;
y = 5;
# swap x and y:
tmp = x; # x = 2, y = 5, tmp = 2
x = y;       # x = 5, y = 5, tmp = 2
y = tmp;     # x = 5, y = 2, tmp = 2
1
2
3
4
5
6
x = 2;
y = 5;
# swap x and y:
x -= y;    # x = 2-5,         y = 5
y += x;    # x = 2-5,         y = 5+(2-5) = 2
x = y - x; # x = 2-(2-5) = 5, y = 2
1
2
3
4
x = 2;
y = 5;
# swap x and y:
x,y = y,x

Which is “better”? Why?

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.

You’ll need these files to follow along:

1
2
# Option 1:
announce(16)
1
2
3
4
5
# Option 2:
num_rooms = 1
while(look_right()):
  move_right()
  num_rooms += 1
1
2
3
4
5
6
7
8
9
10
# Option 3:
width = 1
height = 1
while(look_right()):
  move_right()
  width += 1
while(look_down()):
  move_down()
  height += 1
announce(width*height)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Option 4:
visited_rooms = []
x = 0
y = 0
visited_rooms.append(str(x) + "," + str(y))
while(True):
  next_direction = random.randint(0,3)
  if next_direction == 0:
      if(look_up()):
          move_up()
          y -= 1
  elif next_direction == 1:
      if(look_down()):
          move_down()
          y += 1
  elif next_direction == 2:
      if(look_left()):
          move_left()
          x -= 1
  elif next_direction == 3:
      if(look_right()):
          move_right()
          x += 1
  here = str(x) + "," + str(y)
  if here not in visited_rooms:
      visited_rooms.append(here)
      announce(len(visited_rooms))