Improving Code Readability with High-Level Comments

Reading lots of source code is a great way to learn how to write code that’s faster to read. Unfortunately, I’ve spent hundreds of hours reading source code that could benefit from more organization. The code often comprises long, complicated functions, repetitious blocks, and a sea of low-level statements. It also has very few comments and lacks external documentation. So I must read and remember the entire body of code before understanding the structure and making meaningful contributions to the project.

At some point in my career, I started a new project on a large body of code. Unfortunately, nobody on the team felt very comfortable with it. We had a partially working product and a long list of bugs to fix. On top of that, we needed to add a host of new features. Unfortunately, the original author was no longer available to help. I often heard coworkers say the code was difficult to understand, and they were right. We were eager to make progress but leery of making changes.

I started reading line after line of code and soon realized there would be better ways to come up to speed than reading alone. I became overwhelmed with details and questions about each line of code and how it fit into an overall body of work. I sometimes forgot details about sections I read in the past and had to re-read them to gain context for new areas. I needed a way to remember what I covered better and make the code easier to read in the future.

In desperation to try something new, I started adding succinct, high-level comments to the code. I wrote one-line comments summarizing the most significant coherent blocks I could. Making comments that accurately described everything for a given block was vital. I didn’t write comments explaining complicated algorithms or tell the “why” or those types of things. I just wrote summaries in the language of the problem space. I made no other modifications to the code – just comments.

Writing, in addition to reading, helped me remember the code more quickly. There’s something about writing my thoughts that helps me remember things. It is so for many people. It also enabled the team and me to read the code more rapidly in the future. The summaries I added provided a higher conceptual discourse and functioned like waypoints to navigate the code.

Can we create an example exercise to demonstrate the fundamental concept of this story? Instead of using a programming language, let’s use pseudo-code. Even non-programmers can do this! Your first challenge is reading the story below as quickly as possible. Then, focus on attaining a high-level understanding of it. Time yourself so you can compare your results later. I will include some questions at the end to check your knowledge.

Sample Story One – Long Form

  • Before getting into your car, make sure you are in a safe location and there are no obstacles in your way.
  • Unlock the car using the key or the remote, open the driver’s door, and enter the car.
  • Adjust your seat so you can reach the pedals comfortably and see the road clearly. Adjust your mirrors to give you a good view of your surroundings.
  • Fasten your seatbelt securely.
  • Insert the key into the ignition switch, usually located on the right-hand side of the steering wheel.
  • Turn the key clockwise until you reach the “on” position. In this position, the car’s electrical systems are activated, but the engine is not yet running.
  • Check your dashboard for warning lights, such as the battery, oil pressure, or check engine light. If any lights remain on, consult your car’s manual or take your car to a mechanic.
  • Once you have checked your dashboard lights, turn the key further clockwise to the “start” position. The engine should start. If the engine does not start, release the key and try again.
  • Release the key once the engine has started. The key will return to the “on” position.
  • Check your gauges to ensure that everything is working correctly, including the speedometer, fuel gauge, and temperature gauge. Monitor the car’s behavior, including engine sound and vibrations.
  • If you have a manual transmission, press down the clutch pedal with your left foot and shift the gear to “1” or “Drive” (for an automatic transmission). Slowly release the clutch while pressing the gas pedal to get the car moving. If you have an automatic transmission, simply put the car in “Drive” and press the gas pedal.
  • Exit left from the Maverik parking lot onto 3600W and head north.
  • Proceed until the T intersection at 11400S and turn left at the light when it is safe to do so. You will be traveling west.
  • Take the first left turn into the Harmon’s Grocery store parking lot. Yield to oncoming traffic.
  • Enter Harmons through the main entrance.
  • Find an open parking spot.
  • Slowly approach the parking spot and position your car parallel to the other parked cars, leaving enough space to maneuver and park.
  • Bring your car to a complete stop by pressing the brake pedal.
  • Shift your car into the “park” gear (automatic) or engage the handbrake (manual).
  • Turn off the engine and remove the key from the ignition.
  • Check your surroundings for any obstacles or hazards before opening the car door.
  • Open the car door and carefully exit the vehicle.
  • Close the car door and ensure it is properly locked.
  • Walk around the car to verify that all windows are closed and that the car is securely parked.
  • Walk towards your destination while being mindful of any other cars or pedestrians in the area.
  • Enter the grocery store.
  • Head towards the bakery section, which is usually located towards the back of the store.
  • Once you reach the bakery section, look for the aisle with bread products. This aisle may be labeled “Bread” or “Bakery.”
  • Browse the selection of bread to find the loaf you would like to purchase. Harmons offers a variety of bread options, including whole wheat, sourdough, white, and more.
  • Check the date on the bread packaging to ensure that the bread is fresh. You may also want to gently squeeze the loaf to ensure that it is not too hard or too soft.
  • Once you have chosen your bread, place it in your shopping basket.
  • When you are ready to checkout, proceed to the nearest checkout line. The checkout lanes are typically located near the front of the store.
  • Once you reach the front of the checkout line, place your bread on the conveyor belt and wait for the cashier to ring up your purchase. You can pay with cash, credit card, or debit card.
  • Once you have paid for your bread, the cashier will bag it for you. Take your bagged bread and exit the store.
  • Exit Harmons through the main entrance.
  • Find your car in the parking stall you left it. Walk towards it.
  • Before getting into your car, make sure you are in a safe location and there are no obstacles in your way.
  • Unlock the car using the key or the remote, open the driver’s door, and enter the car.
  • Adjust your seat so you can reach the pedals comfortably and see the road clearly. Adjust your mirrors to give you a good view of your surroundings.
  • Fasten your seatbelt securely.
  • Insert the key into the ignition switch, usually located on the right-hand side of the steering wheel.
  • Turn the key clockwise until you reach the “on” position. In this position, the car’s electrical systems are activated, but the engine is not yet running.
  • Check your dashboard for warning lights, such as the battery, oil pressure, or check engine light. If any lights remain on, consult your car’s manual or take your car to a mechanic.
  • Once you have checked your dashboard lights, turn the key further clockwise to the “start” position. The engine should start. If the engine does not start, release the key and try again.
  • Release the key once the engine has started. The key will return to the “on” position.
  • Check your gauges to ensure that everything is working correctly, including the speedometer, fuel gauge, and temperature gauge. Monitor the car’s behavior, including engine sound and vibrations.
  • If you have a manual transmission, press down the clutch pedal with your left foot and shift the gear to “1” or “Drive” (for an automatic transmission). Slowly release the clutch while pressing the gas pedal to get the car moving. If you have an automatic transmission, simply put the car in “Drive” and press the gas pedal.
  • Exit the parking lot through the main entrance from whence you came.
  • Turn right onto 11400S and head east.
  • Take the first right on 3600W and head south.
  • Maverik will be on your right just before you reach the intersection of 11800S and 3600W. Turn right into the parking lot.
  • Find a parking stall.
  • Slowly approach the parking spot and position your car parallel to the other parked cars, leaving enough space to maneuver and park.
  • Bring your car to a complete stop by pressing the brake pedal.
  • Shift your car into the “park” gear (automatic) or engage the handbrake (manual).
  • Turn off the engine and remove the key from the ignition.
  • Check your surroundings for any obstacles or hazards before opening the car door.
  • Open the car door and carefully exit the vehicle.
  • Close the car door and ensure it is properly locked.
  • Walk around the car to verify that all windows are closed and that the car is securely parked.
  • Walk towards your destination while being mindful of any other cars or pedestrians in the area.
  • Enter the convenience store.
  • Unpack the loaf of bread you purchased at Harmons from your bag.
  • Find a clean surface to work on, such as a countertop or table.
  • Use a bread knife to cut two slices of bread from the loaf.
  • Retrieve a jar of peanut butter and a jar of jelly from convenience store shelf.
  • Use a butter knife to spread a generous amount of peanut butter on one of the bread slices.
  • Use the same butter knife or a clean one to spread a generous amount of jelly on the other bread slice.
  • Place the slice with peanut butter on top of the slice with jelly, with the spreads facing each other.
  • Cut the sandwich in half or quarters, depending on your preference.
  • Throw the sandwich in the trash.

Test Your Comprehension for Story One

Record the time it took you to read the passage above. Let’s see if you can answer some questions about it.

  • What was the story about?
  • Where did the story begin?
  • Where did the story end?
  • How many nearly identical sections did you find?
  • What kind of store is Harmon’s?

Now that you’ve answered the questions above, time how long it takes you to read Sample Story One – Faster Form below. Hint: just read the title and headings and skip the rest.

Sample Story One – Faster Form

  • Title: Making a Sandwich At Maverik With Harmon’s Bread
  • Drive to Harmon’s Grocery store from the Maverik gas station.
    • Unlock the car using the key or the remote, open the driver’s door, and enter the car.
    • Steps excluded for brevity – see Long Form…
    • Enter the grocery store.
  • Buy bread from Harmon’s Grocery store
    • Head towards the bakery section, which is usually located towards the back of the store.
    • Steps excluded for brevity – see Long Form…
    • Exit the parking lot through the main entrance from whence you came.
  • Drive back to Maverik gas station
    • Turn right onto 11400S and head east.
    • Steps excluded for brevity – see Long Form…
    • Enter the convenience store.
  • Make sandwich using bread from Harmon’s and condiments from Maverik
    • Unpack the loaf of bread you purchased at Harmons from your bag.
    • Steps excluded for brevity – see Long Form…
    • Cut the sandwich in half or quarters, depending on your preference.
  • Throw the sandwich in the trash.

How much quicker could you scan the second version than the first version? Reading the high-level outline of a story enables you to understand it much faster. In addition, you can use the headings to find critical elements without reading most of the story. Skipping large portions of text is the most effective way to be quicker.

Did you notice how many duplicate sections there were in the long form? The repetition is typical in computer programs. Adding summaries will enable you to recognize redundant code blocks you can factor out for reuse. Computers can quickly jump to a common chapter in your story and back again without confusion. In other words, writing higher-level software will lead to fewer lines of code since you only have to write any given section once.

What if I asked you a more detailed question like “are the driving directions from Maverik to Harmon’s and Harmon’s to Maverik perfect inverses of each other?” How quickly can you find the answer in the Faster vs. Long Form? You don’t need to re-read the entire story. It’s precisely the same as the version above but with additional high-level summaries. Pretend the Faster Form included all the detail from the Long Form using a collapsable control.

Here’s one more sample story. This time it has a high level in addition to all the low-level detail from the start. See how quickly you can determine what it’s about. Remember to leverage the high-level summaries!

Sample Story Two – Faster From The Start

  • Title: Baking Yams From Your Garden
  • Dig up yams from your garden
    • Choose a spot to start digging, preferably near a yam plant.
    • Use a digging tool like a sharp-tipped shovel or garden fork to loosen the soil around the yam plant. A sharp-tipped shovel will help you loosen the soil without accidentally cutting the yam tuber, while a garden fork can help you lift the soil around the plant more easily.
    • Carefully dig around the base of the yam plant, making sure not to damage the yam. Be sure to dig deeply enough to uncover the entire yam.
    • Gently pull the yam out of the soil by grasping the base of the stem and carefully lifting it out. Avoid pulling too hard, as this can damage the yam.
    • Knock off any excess soil from the yam and place it to the side.
    • Repeat steps 2-5 for each yam plant in the area.
    • Once all the yams are harvested, select a sturdy sack or container to hold them.
    • Place the yams in the sack carefully to avoid damaging them.
    • Once the sack is full, close it securely.
  • Clean and prepare yams for baking
    • Place the yams in a large bowl or sink filled with cold water.
    • Use a scrub brush or vegetable brush to gently scrub the yams under running water, removing any dirt or debris.
    • Rinse the yams thoroughly to remove any remaining dirt.
    • Pat the yams dry with a clean kitchen towel or paper towels.
    • Using a sharp knife, carefully cut off any blemishes or bruises on the yams.
    • Poke several holes in each yam with a fork to allow steam to escape during baking.
  • Bake yams in oven
    • Preheat your oven to 425°F (190°C).
    • Line a baking sheet with parchment paper or aluminum foil to prevent sticking and make cleaning easier.
    • Place the yams on the prepared baking sheet.
    • Brush or rub a small amount of olive oil or melted butter over each yam to help them cook and prevent them from drying out.
    • Season the yams with desired spices, such as salt, pepper, cinnamon, or brown sugar.
    • Bake the yams in the preheated oven for 45-60 minutes, depending on their size and desired doneness. Check the yams for doneness by piercing them with a fork; they should be tender and fully cooked.
    • Remove the yams from the oven and let them cool for a few minutes.
    • Serve the yams hot, either plain or with desired toppings like butter, brown sugar, or cinnamon.

Summary

This post has been about creating a higher level of understanding in your code and how that enables readers to skip over large portions and quickly acquire the gist. Allowing readers to skip code is how you can speed them up most. Take the time to create a high level in the code you maintain. It will help you read it more quickly in the future, and you’ll remember it better, too. While creating a high-level story in comments, try turning your comments into method names. How else might you organize your code to achieve the results shown above? We’ll talk more about conceptual stratification in future posts. Until then, try using the ideas here to write code that’s much quicker to read!