Lecture 34 (Tychonievich) - Good Code

Lecture Date: Wednesday, April 8

What makes good code?

  • 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 looked at the following code for the grid-of-rooms we did in Lab 2:

Tiny
1
2
Robot r = new Robot(4,4);
r.say(16);
Squares
1
2
3
4
5
6
7
Robot r = new Robot(4,4);
int roomsInY = 1;
while(r.check('S')) { // proportional to height
  r.go('S');
  roomsInY += 1;
}
r.say(roomsInY * roomsInY);
Random
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
28
29
30
31
32
33
34
35
36
Robot r = new Robot("xx x\nx  x\n xxx");
ArrayList<String> visited = new ArrayList<String>();
int x = 0, y = 0;
visited.add(x+","+y);
while (true) {
  double number = Math.random();
  if (number < 0.25) {
      if(r.check('E')) {
          r.go('E');
          x += 1;
      }
  }
  else if (number < 0.5) {
      if(r.check('S')) {
          r.go('S');
          y += 1;
      }
  }
  else if (number < 0.75) {
      if(r.check('W')) {
          r.go('W');
          x -= 1;
      }
  }
  else {
      if(r.check('N')) {
          r.go('N');
          y -= 1;
      }
  }
  String here = x + "," + y;
  if(!visited.contains(here)) {
      visited.add(here);
      r.say(visited.size());
  }
}

… as well as general maze solving

From Lecture