Saturday, April 8, 2017

kilo commentary: editorProcessKeypress (step 21)

In part 3 of Build Your Own Text Editor, the following preliminary implementation is presented for a function called editorProcessKeypress:

void editorProcessKeypress() {
  char c = editorReadKey();
  switch (c) {
    case CTRL_KEY('q'):
      exit(0);
      break;
  }
}

It's a very short function, but it's already got a problem: it's doing two different things: 1) reading input from the user, and 2) processing that input. If you're not seeing the problem, imagine if you wanted to use the editor in a scripting environment to modify a file. As it's written above, reading the input from the terminal is a part of editorProcessKeypress. Fortunately, this is easy enough to fix, just move the call to editorReadKey up one level, and pass the result in as a parameter:

void editorProcessKeypress(char c) {
  switch (c) {
    case CTRL_KEY('q'):
      exit(0);
      break;
  }
}

/* ... */

   editorProcessKeypress(editorReadKey());

Note how this also gives us a couple of functions that can be composed together in a nicely satisfying way. Discussion of Curly's Law.

No comments:

Post a Comment