After I wrote about why you should make your code more readable, I decided to take a snippet of code that I had just thrown together and rewrite it so that its purpose was clearer. The code is from a project that a friend and I built to help us learn about developing for the Arduino.

Original Code

In the full program, each time a pushbutton is pressed, a counter is incremented and shown on a 7-segment display (up to a max of 9). When the button is held for 3 seconds, the on-board LED blinks the number of times on the counter, and then the counter is reset. It’s a fairly simple program, but it definitely carried enough of a challenge to be interesting.

The segment below is responsible for blinking the LED.

int i;

for (i = 0; i < counter; i++)
{
  digitalWrite(ledPin, HIGH); //turn LED on
  delay(500);

  digitalWrite(ledPin, LOW); //turn LED off
  delay(500);
}

counter = 0;

The Re-write

I started off by renaming each of my variables to describe why it was there. We had been using the counter variable to store how many times the LED would blink when the button was held down for 3 seconds. Since a “counter” can really be used for any purpose, I figured it would be more descriptive to call the variable numberOfTimesToBlink. It’s a bit verbose, but it lets the reader understand what the code is doing without having to hunt for where the variable was declared.

The next step was to rename i. I thought about naming it something like numberOfTimesBlinkedSoFar, but it didn’t seem to carry any additional meaning. When I thought about it further, I realized that it was the variable that wasn’t carrying any meaning. The problem here was that I put in a for loop where it didn’t really make sense to have one.

Recognizing that I was resetting the counter at the end of the loop anyways, I figured it would make more sense to just decrement the counter each time through the loop such that it ends at its intended final value of 0. In the context of the loop, the variable now means “number of times left to blink”, which matches the way its named.

Final Code

while (numberOfTimesToBlink > 0)
{
  digitalWrite(ledPin, HIGH); //turn LED on
  delay(500);

  digitalWrite(ledPin, LOW); //turn LED off
  delay(500);

  numberOfTimesToBlink--;
}

I don’t have any metric available for “more readable”, but the modified code definitely carries more meaning in fewer lines. I asked a friend of mine to review the code and he agreed that the latter was easier to understand.

When I first wrote the code, it seemed like such an inconvenience. But in the end, thinking everything through really didn’t all that long. The lesson for the future is to always ask myself if my code can be made more readable, and if it can, then do it, either now or soon.