Showing posts with label C. Show all posts
Showing posts with label C. Show all posts

Sunday, February 26, 2012

Enums and Hair Colors

Enums, or enumerated types, are data types that can take on a fixed set of values. The elements in the enumerated set are named, allowing programmers to reference specific elements in an understandable form. These data types allow stricter checking (elements must be one of a limited set) and improved code readability (actual names are used).

"It is blue!" wailed a lady three chairs over.

Angela snuck a glance. Sure enough, the woman's hair was a vibrant, electric blue. Angela turned her attention back to the head in front of her.

"I… I…" stammered Derek. He stood behind the blue-haired woman. His face registered a mixture of shock and fear.

"It is supposed to be blond," screamed the lady. "But it is blue!"

"I know," said Derek. "It is just that… I thought… Umm... let me go check something."

Angela heard Derek rush toward the supply room. Knowing the seriousness of the problem, Angela paused, excused herself, and followed Derek. It was only Derek's first week; he could probably use some help.

Angela found Derek in the supply room staring at a shelf full of dye bottles. The salon's owner Karen stood next to him gesturing angrily.

"I picked the wrong bottle," moaned Derek. "I thought blond was bottle #14, but it was #15. Oh no! What am I going to do?"

"It is not his fault," interjected Angela. After a brief pause she added, "Well, technically it IS his fault. But this system makes it easy to make mistakes."

Karen spun toward Angela, anger in her eyes. "Not this again! I have used this system for ten years. Everyone who works here learns it."

Feeling protective of Derek, Angela pressed on. "It is a bad system. You have 20 different hair dyes in numbered bottles. In order to find the correct dye, you need to either remember or look up the correct 'magic number' for that color. It is too easy to make a mistake."

Karen waved dismissively. "What would you suggest?" she asked. "We already implemented a bunch of your ideas, and they always seem to add overhead. Just last month, we started unit testing the hair dryers. What now?"

Angela noticed the Karen had omitted the fact that the ideas also prevented errors. She decided not to press the point.

"Enums," answered Angela.

"Enums?" asked Derek.

Karen squinted in confusion as if wracking her brain.

"An enumerated type is basically a set of NAMED elements. You refer to an element in the set using its name, instead of some magic number. For example, in this case we could create an enumerated type for hair dyes. It would contain items like BLOND, DIRTY_BLOND, PLATINUM_BLOND, SUNSET_RED, and so forth. Then, to find the correct color, you give the name of the type."

"We tried that," said Karen. "Remember, the stock person could never remember how to spell 'blond'. The bottles were labeled 'blund' or 'bloond'. That is why we started using numbers."

"Enums give the best of both worlds," Angela assured her. "Like the numeric options, you have a limited set of options. And, like the free text labels, you have descriptive names. No more spelling errors. No more memorizing magic numbers."

Karen was silent for a moment. "What will it cost me?" she asked.

From outside they heard a loud, tearful scream. "Blue!!!"

Angela shrugged. "I guess that it will take longer to write the color code on the form, since the name will be longer than a number."

"BLUE!!!" came another scream.

"I think it might be worth it though," Angela added.

-------------------------------

Thank you to David Karl for recommending the topic of enumerated types!

Want to learn more about practical programming tips? Read about the importance of: variable initialization, unit testing, source control, comments, or data validation.


Wednesday, June 29, 2011

Variable Initialization in Busy Kitchens

Variables store values in computer programs. In some programming languages, variables are given a default value when they are created. In other programming languages, including C and C++, variables must be initialized. Until they are initialized they hold whatever value happened to previously occupy that location in the computer's memory. Forgetting to initialize variables can lead to unexpected and undesirable behavior.

The kitchen was hectic. Five chefs and ten assistants were working in a tiny space, preparing the feast for the king's birthday.

"I need another bowl" shouted the dessert chef.

His assistant quickly scurried over to the nearby dish counter and grabbed a bowl. He placed it at the edge of the chef's table before returning to his task of peeling radishes. The assistant knew that efficiency was key in such hectic situations. When the chef needed something, he needed it now.

"What the heck is this?" bellowed the chef.

The assistant trembled as he looked over. Why was the chef angry?

"This bowl is filled with rotten tomatoes! My goodness, they are covered with blue fuzz!" The chef looked horrified.

The young assistant quickly realized his mistake. In his eagerness to get a bowl for the chef, he had forgotten to make sure that the bowl was correctly initialized. In this case, that meant that the bowl was clean and empty. Since the bowls on the dish counter were almost always clean and empty, the assistant had not even thought to check.

Unfortunately, the chef had made the same mistake. He had dumped the pudding that he was making into the bowl before confirming that it was indeed empty. Now the bowl was filled with an unpleasant mixture of the chocolate pudding and rotten tomatoes.

----------------

Wednesday, June 22, 2011

Swapping Array Values and the Swimmy Friends Pet Store

Swapping two values in an array is a basic operations that helps illustrate how arrays store data. Each entry in an array can be viewed as an individual variable -- it stores one piece of information. Thus, in order to swap the values contained two different entries, additional (temporary) storage must be used. Specifically: 1) The data from one array entry is written to the temporary storage, 2) the data from the other array entry is written into the memory location of the first entry, and 3) the data from temporary storage is written into second array entry. For example to swap array entries at indices i and j in C, we might write:


int temp_variable = my_array[i];

my_array[i] = my_array[j];

my_array[j] = temp_variable;


Casey's first day at the Swimmy Friends Pet Store had not gone smoothly. Within fifteen minutes, he had accidentally allowed all thirty turtles to escape. He then spent the next eight hours trying to round them up. Although the turtles were slow, they scattered in different directions and hid under store shelves. No matter how nicely he asked, the turtles refused to come when he called them.


Casey sincerely hoped that his second day would go better.


"Hey, Casey. I have a job for you." called the manager as Casey entered the store.


"Sure!" responded Casey eagerly. He wanted to prove that he was a good employee.


"We are starting a promotion on tiger barbs this week." the manager explained. "I want to put them in the big tank at the front of the wall. Can you swap them with the neon tetras?"


Casey looked at the fish section. The entire back wall of the store was lined with large, brightly lit fish tanks. At the front was the tank currently occupied by the neon tetras. Five tanks over, two dozen tiger barbs swam lazily around a small rock. Both tanks looked quite heavy.


"You want me to move the tanks?" asked Casey. Casey's mind froze as he pictured himself dropping a full 50 gallon fish tank.


"Of course not!" the manager answered. "The tanks are full of water. Just swap the fish. The temperature and PH are already identical."


Casey nodded. He walked over to the tiger barb tank and began trying to scoop up barbs in the net. The manager watched from the side.


"What are you doing?" the manager asked.


"Moving the tiger barbs over." responded Casey without looking up. The tiger barbs were fast, and Casey was not particularly coordinated. He thrashed about with his little green net, hoping that he could at least catch one by luck.


"You do know that tiger barbs and tetras cannot go in the same tank, right?"


"Uh huh." responded Casey, still lost in concentration.


"So, what are you going to do with the tiger barb that you are having trouble catching?" prompted the manager.


"I am going to put it… oh." Casey suddenly realized his mistake. There was no way he could transfer the tiger barbs over without first moving the tetras. And there was no way to transfer the tetras over without first moving the tiger barbs. The whole swap was deadlocked.


The manager watched for a minute as Casey grappled with the problem, waiting for him to see the solution. After all, it was not a hard problem. Finally, the manager realized that Casey was not going to figure it out.


"Just use that empty tank as a temporary storage." The manager prompted. "First, put the tetras in that empty tank. Then move the tiger barbs to the old tetra tank. Then move the tetras to the old tiger barb tank."



Step 1:


Step 2:


Step 3:



"But… that means three sets of moving things. I know that I can do it in two." responded Casey. He was determined to prove that he was a good employee.


The manager sighed. "No. You cannot. You need to use temporary storage. Otherwise, you will end up putting tiger barbs in the tetra tank and causing problems."


Casey wanted to argue, but he could not think of a better solution. "Okay," he finally agreed.


The manager looked at Casey doubtfully. While he was semi-confident that Casey could handle the fish swap, he worried about Casey doing something stupid later.


"Come find me when you are done." the manager instructed. "And, stay away from the turtle tank." he added for good measure.

Sunday, June 19, 2011

The Incident at the North Gate (or Why = Is Not ==)

In many modern programming languages the expression "a = b" is used to assign the value b to the variable a. In contrast, the expression "a == b" tests for equality and returns true if and only if the values of a and b are the same. Unfortunately, in some languages, such as C and C++, this syntax can lead to difficult to detect errors because the = operator returns the value being assigned. For example, "if (a = b)" will compile without problems and trigger if and only if b's value is equal to true.


King Fredrick loved to tell the tale of the "incident at the northern gate". He was a firm believer in the importance of clear, correct documentation. And, the occurrences of that day provided a perfect case study.


The incident had occurred during the last period of war and unrest. King Fredrick's father held the throne and was working hard to guide the kingdom toward peace and prosperity. As part of this effort, he personally oversaw the creation of new rules for the castle guards.


The new rules read:

"Check the entrant's ID and examine their entrance ID class.

IF (ID class == 0): they are a member of the royal family, so let them pass,

ELSE IF (ID class == 2): they are a member of the carpenters' guild, so let them pass;

ELSE IF (ID class == 3): they are a member of the plumbers' guild, so let them pass;"

and so forth. Unfortunately, even a king makes syntax mistakes occasionally. The erroneous line read:

"ELSE IF (ID class = 72): they are a mime, so stop them"

The king had used an assignment statement instead of an equality test.


It took three days for someone to reach this test in the series of IF-ELSE statements. On that day a young hedgehog walker (ID class 185) arrived at the north gate with the King's prize hedgehog. He presented his ID to the guard. The guard consulted his manual and paused in confusion.


"What is wrong?" asked the boy.


"Well. The manual says here that I am to change your ID class to 72 and prevent you from entering." The guard responded. As he spoke he reached into his booth and pulled out a permanent marker. He crossed out the ID class of 185 and wrote 72 in its place.


"But, I am supposed to go inside." argued the boy. "I have the king's hedgehog."


"I am sorry lad. No mimes allowed in here!" responded the guard.


The boy looked confused. "Mime?"


"Yes. It says ID class 72. That means you are a mime!" answered the guard.


"But, you just wrote that. It was ID class 185. I am a certified hedgehog walker. And, I am working on my parrot walking license too. I provide a valuable public service."


"The manual told me to reclassify you as a mime, so that is what I did. And, we do not allow mimes here!" responded the guard formally.


"But…" started the boy.


"Be gone!" shouted the guard.


The boy quickly retreated and circled around to the south gate. Unfortunately, his ID now clearly indicated that he was a mime. He was not allowed to enter. Discouraged, the boy went home, bringing the king's hedgehog with him.


The incident went unnoticed for almost a day, until the king sent a search party to find his hedgehog. Fifty knights arrived at the boy's home, scaring both the boy and the hedgehog out of their wits. It took three hours for the boy to pull himself together enough to explain what had happened. And, it took another five hours to calm down the hedgehog.


The king was furious when he found out. He marched down to the north gate and grilled the guard on why he had changed the boy's ID. The guard pointed to the instruction and explained himself. But when the king saw that this was his own mistake, his mood only worsened. The king launched into a six hour rant and then immediately insisted on three sweeping changes:

1) All IF statements would put the constant value before the variable (e.g., 0 == Class ID), so that no assignments could happen by mistake;

2) Every new set of rules had to be checked by at least one other person for correctness (although this was a great practice in its own right, the king also wanted someone else to blame if there was a mistake).

3) All new rules would be unit-tested by a group of Shakespearean actors.

Despite the seeming overhead of these new regulations, the castle was launched into an unexpected period without any mistakes. Even the castle stables, which had 100 page rulebooks, went a full week without any mistakes.


Feeling satisfied with his contribution for the day, the king decided to get a pet parrot. He had heard good things about parrots recently.


-------------------------


Related stories: Also see the story of how King Fredrick rewrote the instruction castle instruction manuals to use the Switch/Case format in Switch/Case and the Palace Guards. Or read more about the IF-ELSE statement in Learning IF-ELSE the Hard Way.

Friday, June 10, 2011

Switch/Case and the Palace Guards

Switch/Case is a computational construct in many modern programming languages that allows the program to choose one of multiple execution options. The option is chosen by "switching" on the value of an input parameter.


King Fredrick loved performing surprise inspections of the palace guards. Naturally, he felt that these inspections kept everyone prepared. But, more importantly, he found that wandering the grounds for an inspection was the best way to keep the castle steward from finding him. If Fredrick stayed in the throne room, the steward would constantly bring problems to his attention. Sometimes, the king just needed some quiet.


"You there. Guard." called the king.


The guard groaned quietly. Unlike the king, the guards were not fond of surprise inspections.


"Yes, sir!" the guard responded in his best military voice.


"Tell me, are you always at this gate?" inquired the king.


"Yes, sir!" The guard could sense that it was going to be a long day.


"Wonderful. Wonderful. I have some questions about security. If someone comes down the path, how do you know whether to let them in?"


The guard reached into his little guard booth and pulled out a thirty page instruction manual. He quickly opened to the first page, hoping that the king did not see the coffee rings on the cover. It was considered disrespectful to use the official castle manuals as coasters. But, truthfully, that was often their most useful function.


The guard started to read from the manual in a loud military voice:

"Check the entrant's ID and examine their entrance ID class.

IF the person is a member of the royal family (ID class 0): let them pass,

ELSE IF the person is a merchant of a registered guild (ID class 2, 3, or 6): let them pass,

ELSE IF the person is from an opposing army (IF class 107): stop them,

ELSE IF the person is a registered juggler (IF class 71): let them pass,

ELSE IF the person is a registered mime (IF class 72): stop them,

ELSE..."


"Enough!" interrupted the king. The manual was in the familiar IF-ELSE series of conditions of which the past king, Fredrick's father, had been so fond. Why any king would prefer that style was beyond Fredrick. Fredrick was certain that he had updated all the manuals by now.


"It looks as though we need to update your manual." the king stated.


The guard was confused. He also looked scared. "But Sir, I have not made any mistakes. No intruders have been let in and no VIPs made to wait. I have not done anything wrong!"


The king gave the guard a reassuring smile. It did nothing to assure the guard. "No. That is not it. The manual uses a complex format that is simply harder to understand. We switched everything else to switch/case a few years ago. For a long list of conditions like that, it can be cleaner."


"Switch/case?" asked the guard. He did not remember that from his training.


"Yes." the king looked around for a prop to illustrate. Finding none, he started gesturing with his hands.


"Here is how that would work in switch/case." the king began.

"Check the entrant's ID and find the first matching case.

Case Royal Family: let in and done,

Case Enemy: Keep out and done,

Case Merchant of a registered guild: let in and done

And so forth!"


"You just go down the list and find a match. It is the same logic as the long list of nested IF-ELSE conditions. It is just easier to read... Sometimes." finished the king. He loved explaining computational constructs and was debating launching into a description of unrolling loops, when he realized that he could be boring the guard. He had a habit of boring people sometimes. Then again, the guard was nodding intently as the king spoke. Maybe the guard would want to hear about unrolling loops.


"Oh..." responded the guard, clearly thinking this over. "Why do you keep saying 'and done' after each command?"


"Well technically, the way it works is that you go to the first case that matches and keep reading instructions down until you hit a break. That way you can use complex blocks of commands for multiple cases without repeating them. When I say done, I just mean break out of the switch statement."


"Oh... But what if the appropriate condition is not there?" asked the guard.


"You can always have a default case to cover everything else. For you, I would make that 'Keep the person out and call for clarification.'"


The guarded nodded. "Yes. That would seem like a good default. I would hate to have to make a judgement call on my own. But, it seems that you are not actually changing any of the procedures?"


"That is correct." answered the king. "Switch/case can be thought of as a sort of shorthand for a long series of if statements. We will simply clean up the manual… and maybe put something in there about marching bands. Yes. We should certainly have a case about marching bands."


The king trailed off and stared out at the castle wall. Although he could not explain it, he knew that marching bands, mimes, and clowns all needed their own cases. Something about each of them made him profoundly uneasy.


"Well, I shall return to the castle and set to work on a new manual right away." proclaimed king Fredrick. He was excited by the opportunity to update more castle documentation. Given the recent peace in the kingdom, he had not had much real work to do for a while.


This was the best news of the guard's day: an early ending to the surprise inspection.


------------------------


For more information on IF-ELSE statements, see Learning IF-ELSE the Hard Way.


Or for more adventures of King Fredrick, see Hunting Dragons with Binary Search or Stacks, Queues, Priority Queues and the Prince's Complaint Line.

Friday, May 27, 2011

Learning IF-ELSE the Hard Way

The IF-ELSE statement is a computational construct that allows the program to branch off and execute one of two different blocks of code. The IF statement starts by evaluating a Boolean clause. If this clause evaluates to true, the block of code conditioned on this IF statement is executed. If an ELSE statement is present, it can provide a block of code to execute in the case where the Boolean clause evaluates to false.


Ann had learned the value of IF-ELSE statements at a very early age. When she was only three years old, she was given VERY strict instructions from the castle's head chef NOT to randomly eat things in the kitchen. Specifically, she was told:


IF the food is on the 'finished' table

You can eat it.

ELSE

Do not eat it.


Of course, as any three year old is bound to do, Ann ignored these instructions. She would sneak into the kitchen and eat pieces of fruit off of the chef's prep table. Each time that the chef caught her, he would give her a lecture about obeying the IF statement. His lectures would last a full ten minutes and include at least one remark about "kids these days". Ann enjoyed listening to him describe the branching logic of the IF statement almost as much as she enjoyed sneaking fruit. In fact, some days she even made sure that she was caught so that she could listen to his rants.


Then one day, the chef was preparing eight-chili soup for dinner. As the name implies, the ingredients involved eight different types of chilies, including the ultra-hot Dragonia chili. Unfortunately for Ann, the Dragonia chili looked remarkably like a strawberry. She snuck two, and popped them in her mouth. The resulting pain was intense. Ann's eyes did not stop watering for three weeks. After that, Ann never disobeyed the chef's IF statement again.


As she grew older and more responsible, the chef added a chained IF statement to allow Ann access to a wider variety of food:


IF the food is on the 'finished' table

You can eat it

ELSE IF the food is on the 'raw ingredient' table AND you ask first AND the chef says "yes"

You can eat it

ELSE

Do not eat it.


Having learned her lesson from the chili pepper incident, Ann dutifully obeyed this new expanded rule. Food that was on the finished table was always okay to eat. Otherwise, if the food was on the 'raw ingredient' table, she knew that she would have to ask the chefs first. The logic was simple and covered the important cases.


Of course, those rules still did not stop Ann from trying to trick her younger brother into eating Dragonia chilies. She even succeeded -- twice.


-------------------------------------


For more IF-ELSE fun, see The Marvelous IF-ELSE Life of the King's Turtle.

Tuesday, March 29, 2011

The Importance of (Variable) Names

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.

---------------------------