Wednesday, March 30, 2011
Tuesday, March 29, 2011
Having clear, meaningful variable names is an important factor in writing understandable and maintainable code.
￼By the time Princess Ann had reached the northernmost outpost within the kingdom, she was losing hope. Her father, King Fredrick, had sent her on a quest to save the kingdom from impending darkness almost a month ago. So far, Ann had found nothing. Meanwhile reports of roaming dragons and hordes of goblins increased throughout the kingdom. Ann felt completely demoralized.
The outpost of Garroow had been hit particularly hard by the recent chaos. The goblin attacks had been increasing in recent weeks. The commander, Sir Aat, had sent word to Ann's father that the outpost was in desperate need of reinforcements. At a loss for better stops on her quest, Princess Ann headed north to Garroow.
The situation in Garroow was worse than she had expected. During her first night at the outpost, a small goblin attack almost overwhelmed it. The fifty person garrison barely held off just three, relatively lethargic, goblins. She heard the captain shouting orders at his solders: “Ut, guard the South wall. No, I meant Ot. Ut, stay where you are.” “Drex, swap places with Plex, we need an archer on the wall not a blacksmith.” “Et, secure that door.”
Eventually, the soldiers repelled the attack and extinguished the fires. However, the lingering feeling of chaos and confusion continued to bother Ann. It worried her that the garrison's response had been so disorganized. It was like watching a turtle try to chase its own tail. The problem was not the number of soldiers in Garroow, but rather how they were being commanded.
Ann resolved to fix the situation before leaving the garrison. She spent the entire night pondering the different algorithmic strategies, certain that one of them would help the garrison run more efficiently. As she had been taught from an early age: almost every problem has an algorithmic solution. She debated the pros and cons of using dynamic programming to organize communication lines, using a min-max search to optimize strategy, and using randomization to avoid local minima. But none of these approaches seemed to address the core problem. Ultimately, the true issue dawned on her at 3am, and she fell asleep confident that she knew how to fix the situation.
“Sir Aat,” she addressed the commander at breakfast the next morning. “We need to discuss the attack last night.”
“Yes.” agreed the commander. “Now you see why we need the reinforcements.”
“No. I do not.” responded Ann.
The commander looked shocked. The rest of the dining hall fell silent. Everyone waited to see what Ann said next.
“What you need are better names.” Ann continued.
The commander laughed deeply. “You don't understand. We have already improved our names. When a soldier joins the outpost, they are assigned a new name. Every name is short, so that commanders can call out orders quickly in battle.”
“No. It is not.” disagreed Ann. “It is inefficient.”
“No offense Princess Ann, but what do you know about commanding in battle?” he asked.
“Only what I observed last night. But from that limited introduction, I can assure you that the names are hurting your efforts.”
“I think you are mistaken.” declared the commander. “They allow us to issue commands at incredible speeds.”
“Yes they do.” agreed Ann. “But they are prone to mistakes. Last night, you corrected yourself 89 different times. The names are too similar and thus too easy to confuse. Plex and Drex. Ut, Ot, Et, and Aat. The short names do not help!”
“Ha! What would you suggest?” scoffed the commander.
“Use descriptive names. For example, Plex should be called 'South Tower Archer' or at least 'Archer 1'. That more accurately reflects his role.”
“That is crazy!” bellowed the commander as he slammed his mug of coffee on the table. “Do you know how long it takes to say 'South Tower Archer' in the heat of battle? We would waste valuable time.”
“Do you know how long it takes to say 'Drex, swap places with Plex, we need a archer on the wall not a blacksmith.'? Any measure of efficiency needs to take into account the time spent on corrections.” countered Ann.
The commander had no response for that.
“And what about you?” Ann continued. “Why not have them call you Commander or Captain?”
“Our names already reflect rank.” replied the commander. “The names proceed down the ranks in alphabetical order. It allows any solder to instantly know who outranks them! It makes life simple!”
“No. It does not.” corrected Ann again. “In order for the solders to even refer to each other, they have to learn new made-up names. Why not have them learn the ranks instead? Either way they have to learn something new. Only, in this case, the ranks mean something.”
“But we have a good system!” argued the commander.
Ann sighed. “It is like programming a complex algorithm.” she explained. “Using very short variable names can make it feel more efficient to program, because you can type out the code faster. But, in the long run, it can do more harm than good. It becomes easy to make mistakes and difficult to sort out what is happening. Often times, slightly longer names can make a significant difference.”
The commander opened his mouth to argue, but was unable to think of a rebuttal. Instead, he sat at his table, mouth open, with a confused look on his face. After a while he spoke.
“I think you might have a point.” Secretly, the commander also felt a small pang of relief. He had never been fond of his own assigned name. He often found himself day dreaming of his solders snapping a salute and shouting “Yes Commander!” in unison. Maybe this change would not be so bad after all.
That afternoon, the commander changed every soldier's name to be longer, but more meaningful. Over the next few days, the troops stumbled through drills, getting used to their longer names. But soon, Ann began to see efficiency improve.
A week later, on Ann's final night in Garroow, there was another goblin attack. This time the invading force consisted of 10 highly trained goblin special forces troops. The Garroow soldiers turned away the attack with ease.
As Ann left the garrison, she took a small bit of pride in the dramatic improvements in the forces there. After indulging in the brief moment of happiness, she turned her horse East and continued on her quest to save the kingdom.
If you are interested in learning more about writing good code, check out: The Importance of Comments: A Tale of The Baker's Apprentice, The Curse of Excessive Commenting, or The Importance of Unit Testing Magic Spells.
Monday, March 28, 2011
Memory in a computer is a hierarchy. At the very top you have the ultra-expensive and ultra-fast memory called registers. And at the bottom you have mind-numbingly slow but large storage such as a hard disk. Why does this matter? From a programmer's point of view, understanding the memory hierarchy can allow the programmer to optimize the program to work efficiently within this hierarchy. The correct bits of information are kept at the lowest (and fastest) levels. And from a non-programmers point of view, these concepts provide insight into how a computer works.
It has been rumored* that the entire basis of the modern computer memory hierarchy is based off a single late night conversation between Dr. Simon Babbage XI and Chef Louis Von-Register IX (aka the Iron Cache). The two had been arguing late into the night about the most efficient way to organize ingredients in a kitchen. It was a heated debate between empirical evidence and learned rules of thumb. Unfortunately, the argument became so heated that neither of the men realized that they were both proposing the exact same scheme. Ultimately, the night marked both the end of a years' long friendship and a major step forward in computer architecture.
Thus, a good analogy for understanding how computer memory works is naturally to view it in terms of food storage and dinner preparation:
Registers - Registers hold values that you are using at this moment. For example, these could be the inputs into an addition operation in the CPU. This storage is analogous to your own hands or maybe the current mixing bowl. It is literally the "stuff" that you are working with at that moment.
L1 Cache - The L1 Cache holds data that is cached from main memory, but may not be in use at the moment. It is relatively small, but very fast to access. This cache is analogous to the kitchen counter right next to where you are working. You can put stuff down there that you know you will need in just one minute. Just do not leave open containers of milk there all night.
L2 Cache - The L2 Cache is a larger cache between the L1 cache and main memory. It is like the far end of the counter - still easy to get things, but somehow a little more annoying.
RAM - RAM is your kitchen cabinets: larger, but further. You can store a lot more ingredients there than you will need for just the current meal. But, when you are carefully stirring the soup, while trying to keep it at the perfect simmer, it can be a little annoying to run to the cabinet to get more salt.
Hard Drive / Network / Flashdrive - These represent the slow, but very large storage devices. They are the neighborhood supermarket of the memory system. There is a lot of food there, but if you need to go there to get something for a particular recipe, you will probably miss dinner. Ideally, you want to limit your trips to the supermarket and not dash out at every step of the recipe.
Of course most of these levels are conveniently hidden from even low-level programmers. The obvious analogy here is the assistant chef that almost reads your mind by: helping you get the correct ingredients, putting things on the counter, cleaning up unused items from the counter, and running simple errands. Fortunately, the computer's memory system does not get cranky and talk about you behind you back (I think).
*Actually, no such rumor existed until I made up that story. There is probably a much better (or at least more accurate) story for how the computer memory hierarchy came into existence, but I doubt it involves a thrown souffle.