Showing posts with label Marcus. Show all posts
Showing posts with label Marcus. Show all posts

Thursday, November 10, 2011

Names for Ingredients (and Variables)

The use of clear variable names can help make code more readable and reduce the likelihood of mistakes.

"Excuse me. I am looking for powdered rose petals." said Marcus.

"On the shelf behind you." replied the young clerk without looking up. He continued to sit behind the counter, copying text onto a sheet of parchment.

Marcus glanced behind himself to confirm that he had already checked those shelves. Marcus turned back to the clerk.

"I did not see it there." responded Marcus. "In fact, I did not see any ingredients that I recognize. Everything seems to be encoded."

"Shorted," responded the clerk without additional explanation. Before Marcus could ask for clarification, the clerk hopped off his stool and walked around the counter. He proceeded up to the nearest shelf, selected a small bottle, and returned to the counter. He placed the bottle on the counter.

"That will be three copper pieces." said the clerk.

Marcus studied the bottle. It was labeled with large letters: "RP3p". He picked up the bottle and turned it over in his hands, searching for any other markings. There were none.

"Are you sure this is powdered rose petals?" Marcus asked.

The clerk nodded. "Yes. This one clearly states 'RP3p', which means 'Rose Petals Powdered'."

"I see. You abbreviated it. RP for Rose petals and p for powdered. But why the 3?" asked Marcus.

"There is more than one ingredient that can be abbreviated as RP. RP1 is 'Raspberry Puree', RP2 is 'Red Pollen', RP3 is 'Rose Petals', and so forth." answered the clerk.

"That is terribly confusing." exclaimed Marcus. "I have never heard of such a strange system."

A troubled look crossed the clerk's face. "It is my own scheme. It is more efficient." he explained.

"More efficient? You have to figure out awkward abbreviations in order to understand anything." objected Marcus. "It is a wonder that anyone can find what they need."

"But the abbreviations all make sense." responded the clerk. "They are all quite simple actually. How else would you abbreviate 'Rose Petals'?"

"I would not!" answered Marcus. "I would label each ingredient clearly with its proper name."

"But that is so inefficient." complained the young clerk. "Everyday, I have to copy hundreds of potions to sell to patrons. I have to do that all by hand. Do you know how much faster it is to copy potions with this new system? I save hours."

"My word!" exclaimed Marcus. "You sell potions that use this idiotic encoding? Are you serious?"

The clerk did not respond.

"Do you know how dangerous that is? What if one of your customers confuses rose petals and rabbit pellets? It could be a disaster!" argued Marcus.

"But it is more efficient." protested the clerk.

"For you… and at the moment." countered Marcus. "But it makes the potion recipes harder to understand. Worse, it makes it easier to make a mistake."

"But it is shorter." tried the clerk.

Marcus shook his head sadly. "I know it seems faster and more efficient now, but there is a high price for using such shortcuts. It is much better to use clear names. Trust me. I have confused ingredients before; it never ends well."

"You have?" asked the clerk.

"Yes. I once copied down a recipe with 'S' for Salt. Unfortunately, three weeks later, I mistakenly read it as Sulfur. S for sulfur seems quite reasonable. Needless to say, the bread tasted terrible. It was completely inedible."

The clerk did not seem to have an argument for that. "I guess that I could change them back." he said.

"Yes. You should." encouraged Marcus. "Now. Are you absolutely sure that this is the ingredient that I need?"

The clerk hesitated.

"I see." said Marcus. "I will be back some other time then."

And with that Marcus left the store. He turned down a side street and started for the "Potion Ingredients and More" shop on the other side of town. It was a long walk and the prices were higher, but he needed to be absolutely certain that he had the correct ingredients. The last time he had incorrectly mixed up a batch of magic soap, he had ended up smelling like a skunk for a week. There were some things on which he refused to take any chances.

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

Also see Ann's experience with names in The Importance of (Variable) Names.

Thursday, September 22, 2011

Inheritance in Cheeses and Magic Spells: Part 4 of Marcus and the Cursed Cheese

In object oriented programing, inheritance refers to the ability to create derived classes (or subclasses) of a class. These derived classes can reuse attributes or code defined in the original (or base) class. The subclasses are said to inherit the attributes and methods from their base class. In addition, these new classes can also contain code that is specific to the new class itself. This process allows programmers to reuse common blocks of code while still creating more specific classes. [For more information on classes see the previous story].

"Can you tell me anything more about the visitor?" asked Marcus. He was very worried.

The foreman thought for a moment, but shook his head. "Only that he asked a lot of questions and seemed particularly interested in an outgoing shipment of cheese."

"This is bad," stated Marcus.

"Why?" asked both the cheese minstrel and the foreman.

"The wizard that cursed my cheese did so without knowing what type of cheese it was." Marcus explained.

"So? Is there really a difference in cursing different types of cheese?" asked the cheese minstrel.

"There can be a big difference." answered Marcus. "All classes of cheese are derived from a common 'Cheese' base class. Thus they inherit certain properties and actions. For example, all cheese is created from milk. And all cheese has a weight, density, etc. So to that extent, you could target a spell at the base class of cheese itself. All you would need to know is that you are dealing with some class of cheese."

"But, in addition to the inherited properties, each class of cheese has properties of its own." continued Marcus. "For example, some cheeses cause a little popping sensation when eaten."

"Likely Patagonian Popper?" asked the cheese minstrel. Honestly, he was more interested in the cheese aspect of this story than in the magic spells.

"Yes. Exactly." confirmed Marcus. "Knowing which subclass you are dealing with has certain advantages. For example, you can tailor your spell to easily hide within the specific properties of the cheese. In this case, I thought that the wizard who cast this spell was explicitly using the fact it was bleu cheese."

"But since we do not label the boxes with cheese type, the wizard must not have known what cheese he was dealing with." finished the foreman.

"Yes. And that means that we have a very sophisticated wizard on our hands." confirmed Marcus. "Since the shipping labels have the names on them, he could also target my cheese directly. Was anyone else here that might have seen him?"

"Only Sam, the logistics manager." answered the foreman. "But he is having some personal issues at the moment."

"What sort of issues?" asked Marcus.

"He became unnaturally obsessed with some salesman routing problem. He claimed that he could revolutionize my cheese sales if he just solved it. But after 2 weeks, he had not made any progress. I finally had to send him home."

"The traveling salesman problem." Marcus whispered under his breadth. Then louder: "When did this start?"

The manager thought for a moment. "You know, it was right after that visitor."

Marcus nodded. "I have seen this curse before -- the spell of Unnatural P=NP Obsession. It is a powerful spell. Luckily for you, I am one of three wizards in the kingdom that can break this spell."

The moment he said those words, Marcus realized a few things. First, he knew why he had been targeted with cursed cheese. Second, the kingdom was in grave danger. Third, and most shocking, he was not longer hungry for cheese.

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

See how the saga of the cursed cheese began with Part 1: Data Validation, Marcus, and the Cheese Minstrel. Or read about Ann's discover of the spell of Unnatural P=NP Obsession during her trip to G'Raph.

Or if you think the cheese minstrel has it bad, also check out the plight of the king's hedgehog walker in The Incident at the North Gate (or Why = is not ==).

Want more updates and commentary? Follow CompFairyTales on Twitter or follow the author (Jeremy Kubica) on Google+.

Saturday, September 17, 2011

Classes of Cheese: Part 3 of Marcus and the Cursed Cheese

In objected oriented programming, a class defines the type of an object. In particular, an object's class defines the data and methods for that object. Alternately, the individual objects in a program can be viewed as specific instances of a class.

There were stacks of cheese everywhere. The tables were covered with half-filled containers of bleu cheese, brie, feta, mozzarella, and ricotta. Along the wall were large wheels of cheddar and blocks of swiss cheese. It smelled like a good cheese shop should. Marcus suddenly realized that he was incredibly hungry.

"Pardon the mess," started the foreman. "We are in the middle of packing today's soft-cheese shipment."

"There is so much cheese." the cheese minstrel breathed quietly. He was in awe. Never in his life had he been around so much cheese. And for a cheese minstrel, that is saying a lot.

"And over at that table, we are preparing for our shipment of the Swiss Cheese class." added the foreman while motioning to a table covered with blocks of swiss cheese. There had to have been at least fifty blocks of cheese on the table, stacked into neat piles.

"Class?" asked the cheese minstrel. Before the foreman even started to answer, the minstrel had his pad of paper out and was ready to record every detail.

"Yes. Those cheese blocks were all formed by our machines using the same recipe." answered the foreman. "We simply tell the machines: make a block of the swiss cheese class. The blocks have different attributes, such as size or number of holes, but they are all instantiations of swiss cheese."

The foreman walked over to the swiss cheese table. "Take these two blocks. We would describe both as Swiss. They are described by the same internal attributes, such as: weight, size, number of holes, sourness, etc. Granted, they actually have different values for those attributes depending on the specific block, but the attributes themselves are the same. And they have the same range of behaviors, such as EmitSmell."

"Emit smell?" asked the cheese minstrel without looking up from his notepad.

"Yes. Cheese does not have many actual behaviors, but it certainly does smell. Come have a sniff of our new triple-mold ultra-bleu cheese. I think that you will find it most interesting."

Marcus shook his head to try to clear away his current cheese-inspired trance. He had been staring at the massive quantities of bleu cheese for the better part of the conversation. His stomach was rumbling, but he had a mission. He needed to determine who had cursed his cheese. "Can you tell me what your visitor was looking for?" he asked.

"I am not sure. He just wandered around for a little while muttering to himself. He stopped and looked at some of the outgoing cheese shipments. But that was all. He never touched anything."

"Boxed or unboxed?" asked Marcus. "Was the cheese already packaged?"

"Uh..." the foreman seemed confused. "I think it was already in its boxes. Why?"

Marcus did not answer. His mind was racing. It was worse than he had thought.

To be continued in Part 4: Inheritance in Cheeses and Magic Spells...

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

See how the entire saga of the curse cheese began in Part 1: Data Validation, Marcus, and the Minstrel of Cheese

Sunday, September 11, 2011

Objects, Encapsulation, and Cheese Factories: Part 2 of Marcus and the Cursed Cheese

In object oriented programming, objects are types of data structures that include both data and methods for operating on the data. By including both the data and the methods in the same structure, it allows each object to trivially work with its own data. One of the major advantages of objects is that they allow easy encapsulation. Internal data can be hidden from external code and thus only be operated on by the object's own methods.

"I assure you that I inspect all of that machines daily. There is no way that they could produce any inferior cheese. We maintain the highest standards!" argued the foreman.

"I am not claiming that your cheese was inferior, spoiled, or even contained bog dragon droppings. I am not questioning your cheese making standards or your ability to maintain them." argued Marcus. "What I am saying is that the cheese was CURSED. Curses do not happen by accident. This was intentional."

After fifteen minutes of arguing, Marcus was already exasperated. He was on a mission to determine who had cursed his cheese, and the foreman of the Cheswick Castle Cheese Factory was not being helpful. It was not as if the foreman was intentionally dodging Marcus's questions; he simply seemed unable to accept that anything could be amiss with his cheese. Cheswick Castlle was known across the kingdom for producing superior quality cheeses.

"That is simply not possible." countered the foreman. "I would know!"

"How?" asked the cheese minstrel, who had been quietly standing off to the side and scribbling notes. He had promised Marcus that he would not get in the way. So he really did not want to interfere with this discussion, but this seemed like an important point for his new "Ballad of the Cheswick Cheeses". The minstrel wanted to make sure that he got the details correct.

"Yes. How?" added Marcus. "I already told you that this particular curse only targets wizards."

"We have a very sophisticated cheese making process here. We use the latest cheese making objects. They are fully self-contained." explained the foreman.

"Cheese making objects?" asked the minstrel. In all of his years as a cheese minstrel, he had never heard of cheese making objects. He suddenly wondered if he was failing as a cheese minstrel. The self-doubt was crushing.

"He means machines." explained Marcus. Then turning to the foreman, Marcus asked "Why do you call them objects?"

"It was something a recent visitor said," explained the foreman. "He was very impressed with the machines, and he spent a good hour looking one over. He said that the machines were like objects -- they contain both attributes and methods to work with those attributes. The attributes are things like temperature, tray orientation, or humidity. And the machine can operate on these with methods like Bake, Cool, or SpinTray. That way the operators do not need to work directly with the internal attributes, they can just use the externally facing methods."

"Isn't that the case with most machines?" asked Marcus. "That is what makes machines different from something like the minstrel's notebook. The notebook contains data, but cannot do anything with it. It just stores it." Marcus was unimpressed, and he was beginning to think that the foreman was stalling.

"Well..." The foreman thought for a while. "I think you are correct. But our machines are top of the line."

"How do you know?" asked Marcus. "One of the advantages of encapsulation is that you do not need to know about the internal workings. Even the values of the attributes can be hidden from you. How do you know the temperature is correct? Or that the machines even use a process involving temperature? Maybe the machines just bake the cheese at a random heat for a random period of time. All you know if that you get good cheese at the end."

"Ah." The foreman smiled. "In addition to consistently producing superior cheeses, we also have created an extensive suite of unit tests to confirm that the machines are doing what we expect. Here at Cheswick Castle, we maintain the highest standards."

"Yes. But do you test for curses targeting wizards?" pushed Marcus.

"Well... No." answered the foreman. He suddenly looked very worried.

"Tell me more about this visitor." commanded Marcus.

"I can't tell you much." answered the foreman. "I never got his name. He wore a long, dark cloak. He claimed that he was here to inspect the machines, but he only looked at one. He spent an hour with it."

"Can I see the machine that this visitor was so obsessed with?"

Marcus had to admit that the machine was impressive. It must have stored and controlled over a hundred different variables that represented the cheese's current state. But all of that complexity was hidden from the operator behind a simple, clean set of controls.

Unfortunately, a quick check of the machine revealed no signs of a curse causing subroutine.

"Did the visitor look at anything else?" inquired Marcus.

The foreman, now sufficiently panicked, nodded vigorously. "He wanted to see our shipping facility. He said something about wondering where all our cheese went."

Marcus was certain that in the shipping area, he would find both stacks of cheese and a list of wizards awaiting their shipments.


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

Read about how Marcus met the cheese minstrel in Part 1: Data Validation, Marcus, and the Minstrel of Cheese.

Or read about Marcus and the importance of unit testing in The Importance of Unit Testing Magical Spells or good version control in Version Control in Magic Spell Development.

Thursday, September 1, 2011

Version Control in Magic Spell Development

Version control refers to the process of managing changes to a piece of work, such as a computer program. One of the primary benefits of a version control system is that is maintains previous versions of the work. This is important for both: backing up the work against unexpected loss and allowing the developer to access previous versions of the work. For example, a developer might want to revert some part of the work back to a previous state (e.g., reverting a function to before a bug was introduced).

The wizard Marcus kept his apprentices very busy. In his opinion, work was the best way for them to learn. Plus, it was quite convenient to have someone help with the less glamorous work. It was not as though Marcus actually wanted to do any of that work himself; he had more important things to do, such as developing new spells.

Developing new spells was Marcus's favorite task. There was a deep challenge to creating a new spell. First, you had to determine what you wanted the spell to do. Second, you had to determine the overall flow of the spell. Third, you had to isolate and develop the subcomponents of the spell. How would you initiate the transmogrification? How would you know when to stop? He likened the process to writing a symphony or to creating a complex computer program. It could take him months to create the perfect spell.

And that is why Marcus was a firm believer in the importance of version control.

At the end of every day, he would have his apprentice copy down all of his notes onto a fresh roll of parchment. This meant all notes -- a perfect copy of the current state of Marcus's notebook. The apprentice would label the parchment with that day's date and file it in a special drawer. Thus, if Marcus ever needed access to an old version of his work, he could simply retrieve the correct parchment.

One day, his apprentice Shelly started to complain bitterly. "Why do I have to keep copying down your notes? You have everything in your notebook already. And you are just going to change things again tomorrow. Like this paragraph on mixing the potion. Yesterday, I copied down almost exactly the same thing. Except today you crossed out 'Stir 3 times clockwise' and replaced it with 'Stir 4 times counter-clockwise'. Why did I bother copying it down yesterday? Why not just wait until you are finished?"

"Two reasons." Marcus began calmly. He enjoyed explaining the logic behind good spell development almost as much as he enjoyed spell development itself. "First, for safety. Do you remember that time last month, when I accidentally set the room on fire? It was while I was working on the spell to cure dry skin. My lab notebook completely burned up."

"But, sir." protested Shelly. "That was an exceptional case. How often do you accidentally set your notebook on fire? Is it really worth that much effort? Couldn't you just make a copy of the final product? That way you would never loose a spell that is finished. You could only loose parts of unfinished work."

Even as she spoke, Shelly considered her own question. In the one year that she had been Marcus's apprentice, he had managed to accidentally set five different notebooks on fire. Maybe he did have a point about backing up his work. Or perhaps a better solution would be for him to avoid working on spells involving fire. She quickly decided not to raise either of these points.

"I would have still lost days of valuable work!" exclaimed Marcus. "A complex spell might take months to develop. It is simply not worth the risk."

"Then why not just use a magic mirroring spell on your notebook. Surely, you do not need a whole new copy each night. You could just have a single, identical copy in some safe location -- like New Pompeii." argued Shelly.

Marcus smiled. "I do that too. I mirror all my notebooks to a castle out in the country. But there is another reason to copy my notes: developing the a spell is not always a straight line process. Sometimes, I make mistakes and need to go back to what I was doing before."

Shelly looked confused.

"Remember when you copied down the spell for silencing marching bands?" Marcus asked.

Shelly nodded. Of all the spells that she had seen Marcus develop, that was one of her favorites. She had tried it at half-time during her brother's high-school bocce game. In the middle of a song, all of the instruments had gone completely silent. All of the band members were completely confused. Of course, Shelly still felt a little guilty that she had not bothered to learn the reverse spell.

"During the middle of developing that spell, I changed a block at the end." continued Marcus. "I removed all of the instructions for using the wand and started over. I threw out two weeks worth of work."

Shelly remembered clearly. She had muttered a lot of nasty things under her breadth when she had seen the paragraphs crossed out.

"But then what happened?" asked Marcus.

Shelly thought back. "You put them back in a few days later."

"Yes!" agreed Marcus. "It turns out that I had not factored the wind into the spell yet. So I was just able to modify the wording. The original wand instructions were fine."

"I don't understand." sighed Shelly.

"Version control allows you to go back and recover previous versions. If I change my mind and alter an instruction, then I cross it out in my notebook. It is gone from my notebook and the mirrored copies. But I might need to be able to go back and look at the old version. There might be something there that I need later."

"Why not just keep everything in the current notebook?" asked Shelly. "You could add comments saying 'Don't do this' or 'Ignore this' so that you know which instructions are old. That way you would never need to throw anything out."

"That would be too messy. How would I ever read a spell?" argued Marcus. "Version control is cleaner. I can make whatever changes I want, and I know that I can always go back to a previous version if I need it."

"But…" started Shelly, but she had run out of arguments. She could clearly remember many instances when he made major changes to a spell, and then had backtracked the next day and reverted them. During the development of the Spell of Singing Rocks, he had gone back and forth three times on a single approach. Each time he changed his mind, she had been able to retrieve an old scroll so that he did not need to start from scratch.

"But… my hand hurts from copying the same instructions over and over." Shelly finally admitted.

Marcus tried to look sympathetic. "I know that it can be a tiresome task. That is why I have apprentices do it for me."

His statement did not make Shelly feel any better.

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

Check out other valuable lessons learned by apprentices, such as the Value of Good Comments or the Importance of Unit Testing.

Or read about Marcus's castle in the country in Pointers and Walk-In Closests.

Thursday, August 25, 2011

Data Validation, Marcus, and the Cheese Minstrel: Part 1 of Marcus and the Cursed Cheese

Data validation is an important practice to ensure the security and robustness of a program. In short, data should be checked to confirm that it is valid (e.g., no null pointers), non-malicious (e.g., no escape characters in input strings), and of the expected form. Data input into the program should be validated to prevent invalid or malicious data from causing undesirable behavior. Even within the program, data coming into functions should often be validated to protect against accidentally passing a bad value.

It was by pure chance that the wizard Marcus ran into the Minstrel of Cheese. To be certain, the Minstrel of Cheese did not look like a typical minstrel. He was wearing a shabby, bland outfit that was covered with numerous patches. He was sitting against a large oak tree, and there was no sign of a musical instrument in the immediate proximity. In fact, the only object the minstrel appeared to have with him was a very large block of cheddar cheese.

"Excuse me." started Marcus. "I am trying to find my way to the Castle of Cheswick. Would you happen to know the way?"

"It is not a real castle, you know. It is a cheese factory." responded the minstrel.

"Yes. I am aware of its function." answered Marcus. "What I am not aware of is its location."

"Why do you want to go there?" inquired the minstrel.

"Is this a test?" asked Marcus. He was suddenly suspicious. In his experience, only trolls asked random travelers this many questions; and questions from trolls rarely ended well.

"No." answered the minstrel with a long sigh. "I am just curious. You see, I am the cheese minstrel. I am commissioned to tell stories about cheese. So I am naturally interested in anything to do with Cheswick Castle."

"A cheese minstrel?" asked Marcus in disbelief. "I have never heard of such a thing."

"We are not exactly the most highly regarded minstrels in our community." answered the minstrel. "We do not get to sing about knights, dragons, or epic tales. It is actually rather demoralizing. But that is what I get for partying during minstrel school. My mother always told me to take it more seriously, but I didn't listen. Now, I am working on a song about cheddar." the minstrel waved weakly in the direction of his large block of cheese.

"I see. I am sorry to hear that. But I really am in a hurry. Can you tell me where Castle Cheswick is?" Marcus prompted.

"Are you on an important mission?" asked the minstrel with a gleam in his eye. "There are not many important missions that involve cheese factories."

"Yes. I am." answered Marcus. "I believe that there is something foul going on at Castle Cheswick."

"Oh…" The Minstrel sounded disappointed. "That is probably just one of their new varieties. Some cheeses smell stronger than others."

"That is not what I meant. I recently received cursed cheese." explained Marcus.

"Cursed cheese?" asked the minstrel. "I am not familiar with that type."

"It is not a type of cheese. It is a cheese with a curse on it." replied Marcus. "A very particular type of curse that targets wizards with knowledge of computational spells. It is a subtle curse too -- easy to hide in something strong like bleu cheese."

"Then how did you find it?" asked the minstrel. From the minstrel's body language, it was obvious that this conversation was the most exciting thing to have happened to him in the last five years.

"I validate all my food, of course." stated Marcus. "Every good wizard should. Although, admittedly, too many get lazy."

"Validate?" asked the minstrel. "Do you mean you sniff it to make sure that it is not spoiled?"

"I am a little more thorough than that!" proclaimed Marcus. "It can be a big problem if the food that you get is not what you are expecting. You need to validate it. I have caught many problems in the past with my groceries, including:
- the wrong type of food (apple butter instead of peanut butter),
- food containers that are empty,
- expired food, and
- now, cursed food.
But this is the first time that I have seen a spell this well designed."

"So these problems were all intentional?" asked the minstrel in awe. "You must be very important to have so many people trying to mess with your food."

Marcus would assume that the topic of validating one's food would be standard knowledge for someone who spent his life sing epic songs about cheese. But the minstrel seemed to be hearing all of this for the first time.

"Of course it is not all intentional." answered Marcus. "The problems fall into a few categories. There are certainly cases where people do send malicious food, such as cheese with a hidden curse. But there are also other cases, such as getting the wrong food due to a miscommunication or an error on the grocery store's part."

"I remember this one time where I asked for a delivery of twenty loaves of rye bread. They gave me thirty loaves of whole-wheat. What a mix up!" Marcus chuckled.

The minstrel looked confused. "You just said that someone had cursed your cheese and now you are laughing about the wrong type of bread? That sounds like two different problems to me."

Marcus shrugged. "Two different problems, but the same point: you have to validate you input."

"And there is also the related problem of validating the inputs to recipes that have subcomponents." added Marcus. "Even though you have control of the inputs does not mean that you do not have to check them. For example, you always need to check that you made the pizza dough correctly before making the full pizza. I once had an apprentice that did not check her dough, and the entire pizza fell apart in the oven. It took her three hours to clean up the mess."

"And then there was incident with the undercooked pasta." continued Marcus.

"To the north." interrupted the minstrel.

"Huh?" asked Marcus. He had been enjoying explaining the concepts behind food validation.

"Cheswick castle is to the north." explained the minstrel. He paused for a moment. "Can I come with you?" he asked.

"Why on earth would you want to come with me?" asked Marcus. "Didn't I just mention the cursed cheese?"

"You are on an epic adventure to find out who placed a curse on your cheese. It is the opportunity of a lifetime for a cheese minstrel like myself."

"Well... Alright." agreed Marcus. It was not possible to argue with that logic. Where else was a cheese minstrel supposed to go?

The minstrel beamed as he collected his block of cheese and prepared to follow Marcus. Together the two of them set off toward Cheswick Castle.


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

For more practical tips, also see: how Marcus teaches the Importance of Unit Testing Magic Spells, the problems that can arise from forgetting Variable Initialization in Busy Kitchens, or the Importance of Good Comments in Bread Recipes.

Thursday, June 16, 2011

Unhappy Magic Flowers and Binary

Binary is a number system where each digit can only take one of two values: zero or one. Binary is used within computers, because it allows the computer to encode information in a series of switches that are either on (1) or off (0). Each digit of binary represents a power of two. The first (right-most) digit represents the 1's place, the second digit represents the 2's place, the third represents the 4's place, and so forth. For example, the binary number 10110 = 1*2^4 + 0*2^3 + 1*2^2 + 1*2^1 + 0*2^0 = 22 in decimal.


The deliveryman paused outside of Marcus's house. He stood transfixed, staring at the flowers. After two minutes, Marcus finally went outside to see what the problem was.


"Your flowers have changed since yesterday." observed the deliveryman. "I am sure that the one on the right was red yesterday. Today it is blue."


"No. Those are the same flowers." responded Marcus. "Some of them are just sulking today. Stupid flowers."


"Sulking? Do flowers sulk?" the delivery man asked.


"These flowers do. They are, of course, magic. If there is not enough rain, they sulk. It is quite aggravating really. It is not as though they are not getting water. I water them every day. Yet, they still insist on sulking when there is no rain. It appears that the water I give them is not good enough for them."


"Huh?" The deliveryman looked most confused. He looked back and forth between Marcus and the flowers.


"They sulk by changing to blue. Roses are supposed to be red. That is why so many poems start out that way. But, they insist on telling me how long it has been since it rained." Marcus gestured angrily at the roses as he spoke.


"They talk to you?" The deliveryman took a step back away from Marcus. He looked as though he was ready to run.


"Of course not. They simply change color." Marcus sighed.


"And, that tells you how long it has been without rain?"


"Well…" started Marcus. "They used to all change color together after three days without rain. A sort of mass protest. But, then they started to organize. They want to let me know exactly how unhappy they are. So, now they count the days."


"But… only two are blue. It has not rained all week." observed the deliveryman.


"Nine days to be exact." corrected Marcus after looking at the flowers. "They use binary."


"Huh?"


"Binary. Red flowers are zero and blue flowers are one." Marcus added.


The deliveryman did not look as though he was following. But, at least he did not look like he was about to run away anymore.


"Binary?" prompted Marcus. "Each flower represents a different digit, and thus a different power of two. The rightmost flower means one (2^0), the one next to it means two (2^1), the one next to that means four (2^2), and so forth. Add up the numbers represented by the blue flowers and you get the total number of days. Right now only first (2^0 = 1) and fourth (2^3 = 8) flowers are blue, so it has been 2^0 + 2^3 = 1 + 8 = 9 days."


The deliveryman looked. Sure enough, the five flowers across Marcus's porch were: Red Blue Red Red Blue (or 01001).



"Why do they use binary?" asked the deliveryman.


"They tried to spell out the numbers on their petals and they got too confused. So they had to settle for each flower being either all red or all blue. It turns out that flowers are not that smart. Binary is a simple enough system for them. If they were smart enough for anything else, do you think they would be complaining to me about the rain? There is nothing I can do!" Marcus shouted the last part directly at the flowers.


"But, how do they work together?" The more absurd the story got, the more interested the deliveryman became. He took a step forward towards the flowers.


"It is really quite simple for them to count in binary. When it rains, they are all happy and turn red. It is like reseting the counter to 00000. I like those days a lot." started Marcus.


"Then, each morning all of the flowers wake up and decide what color they are going to be for the whole day. If it has not rained, they increase the count.

After 1 day they are: Red Red Red Red Blue (00001 = 1)

After 2 days they are: Red Red Red Blue Red (00010 = 2)

After 3 days they are: Red Red Red Blue Blue (00011 = 2 + 1 = 3)

After 4 days they are: Red Red Blue Red Red (00100 = 4)

After 5 days they are: Red Red Blue Red Blue (00101 = 4 + 1 = 5)

And so on.


"You see, each flower looks to its right in order to decide what to do. If its right-hand neighbor changes from blue to red (1 to 0), then the flower flips its own color. I like to think of it as passing along the unhappiness. Basically, if its neighbor is changing from blue to red then the sullenness is rolling over to the current flower. If it is red, then it becomes blue. And if it is blue, it becomes red and passes the sullenness further down the line. This keeps happening until one of the flowers does not change from blue to red."


The deliveryman thought about it. "What if a flower changes from red to blue (0 to 1)?"


"Its neighbor does nothing. Didn't I just say that?" Marcus was impatient. He felt like he was talking to one of his apprentices. "Think about it the way you would counting with numbers 0-9. When you hit 9, you roll the first digit back to 0 and increment the next digit to 1. That next digit stays where it is until its right-hand neighbor switches from 9 to 0 again. You don't count 10, 11, 12, 23. Do you? NO! You wait until the digit to your right rolls over. Only here there are exactly two options 0 and 1, so things roll over more frequently."


"What about the right-most flower?" asked the deliveryman. "How does it know what to do?"


"Ah. THAT ONE IS THE INSTIGATOR! I am sure that he is the one that started it. Every morning there is no rain, he flips. He is the one that starts the process off. Red to blue to red to blue to..."


"And that system always works?" interrupted the deliveryman.


Marcus tore his attention away from the right-most flower. He suddenly wondered how the discussion had gone from a rant about magic flowers to counting in binary. Did the deliveryman not have any other deliveries? For that matter, where was the delivery for Marcus?


"Yes. They already counted out nine days, haven't they?" answered Marcus flippantly.


Then, seeing the look of interest on the deliveryman's face, Marcus returned to his teaching tone. "Imagine that these three flowers were blue." explained Marcus as he pointed to the first three flowers. "That would be 1 + 2 + 4 = 7 days without rain. The next day the first flower (1) switches to red, so the second flower (2) switches to red, so the third flower (4) switches to red, so the fourth flower (8) switches to blue. Then they would show 8 days without rain. The count effectively gets pushed down into the fourth flower."


The deliveryman looked impressed. Marcus could not understand why. The flowers were really very annoying.


"So tomorrow they will be: Red Blue Red Blue Red (01010)?" asked the deliveryman.


"Probably. But, I really hope that it just rains." responded Marcus with a sigh.

Monday, May 16, 2011

The Importance of Unit Testing Magical Spells

Unit tests are small tests designed to exercise specific components of a program, such as individual functions. The goal is to test components in isolation, allowing for: more targeted and thorough testing, quicker detection of errors, and finer grained debugging. Further, ensuring the correctness of the low level building blocks helps to better ensure the correctness of the overall program. Unit tests can also easily detect low level errors that might be masked by other logic in the program.


Marcus did not become a master wizard by being lazy. Unfortunately, it seemed as though the apprentices these days did not appreciate the value of hard work. His newest apprentice, Shelly, was obsessed with moving onto complex spells.


"You have to master the fundamentals first." Marcus insisted.


"But, I already know the fundamentals." Shelly responded petulantly.


Marcus sighed. Kids these days were so difficult. In his day, an apprentice did not argue with his or her master. You listened and were respectful. Why was everyone suddenly so impatient? Marcus blamed the latest pop culture fad: marching bands. Sadly, there was only one way to reinforce the value of correct building blocks.


"Okay." Marcus responded. "Today we will do the spell of Transmogrified Mold, which transforms ordinary house mold into a candy. It is a complex spell that requires six potions and three hours. Are you able to handle that?"


"Yes!" agreed Shelly readily. She was visibly bouncing with excitement.


Marcus smiled as he handed her the directions. "Here you go then. There should be plenty of mold in the kitchen. I believe a certain apprentice has not cleaned there in weeks."


Ignoring the comment, Shelly ran off to the kitchen to begin the spell.


The key to the spell of Transmogrified Mold was correctly making each of the six potions. If any one of the potions is off by even a little, the product is a complete failure. Granted, the result will still look, taste, and smell like chocolate. However, it will cause three hours of intense nausea and powerful hiccups. Together, those turn out to be a most unpleasant combination.


While Shelly buzzed around the kitchen working, Marcus decided to take a nap. No need to remind Shelly to test each potion individually. By this point in her training, the value of testing should be ingrained. Of course, young apprentices always complained that testing their potions slowed them down too much. But, there was really only one way to learn the value of unit testing potions.


Three hours later, Marcus was woken by the sound of loud vomiting. "I believe she is done." he mumbled to himself as he made his way down to the kitchen.


There he found Shelly, with her head in a bucket.


"How did it go?" he asked.


"I don't know what went wrong." moaned Shelly between hiccups.


"Well, let me just see." offered Marcus. He wandered over to the counter and started testing the individual potions.


The first three were correct.


"Ah. Too much vinegar in the fourth potion. Common mistake. My guess is that you did not notice, because there is too much salt in the last potion. Yep. There it is. All very common."


"But, they all looked correct." Shelly protested between powerful hiccups. "And the end result seemed to work out."


"You will be fine in another two hours and fifty three minutes. Until then, I would recommend keeping a bucket close." Marcus advised.


He paused at the door on his way out. He did not look back as he spoke. "And in the future, I would encourage you to thoroughly test each individual component of a spell. You need to make sure the fundamentals are correct before building off of them. Otherwise, you can find unpleasant surprises."

Monday, April 25, 2011

Checkpointing Checkers

Checkpoints are a technique for improving a program's fault tolerance by preserving the program's state. Checkpoints can be used to recover after a program crashes or used to save the state for later analysis. They are literally dumps from the program that are sufficient to reconstruct the program's current state.

The Powerful Wizard Marcus was traveling to the city of South Atlantis for the annual World Checkers Championships. The competition was legendary, and it attracted all of the best checkers players in the known kingdoms. This year the heavy favorite was Jennifer "King Me" Stratovarious. She had won thirteen of the major competitions in the last six months. Some people said that she was unbeatable. Any match where she played was guaranteed to be exciting. And, Marcus had front row tickets to the finals.

However, Marcus realized that there was a problem as soon as he arrived at the preliminary rounds. The players were playing a frantic pace. They almost looked panicked.

"What is going on?" Marcus asked King Fredrick, who had also journeyed to South Atlantis to watch the world championships.

"They are playing checkers." answered the king.

"I can see that. But, why are they playing so quickly? It almost looks as though they are trying to race through the game."

The king shrugged and returned to watching Jennifer quickly destroy a young novice from South Patagonia. Marcus had never seen a game won in so few moves. Or, for that matter, played so quickly.

Unfortunately, all too soon he understood the reason behind the players' urgency. South Atlantis happened to be the windiest city in the world. Twenty-three minutes into the preliminary round, the entire building started to shake with the force of an industrial paint mixer. Despite the strong walls and shuttered windows, wind swept through the hall. The oil lamps swayed dangerously, people fell down, and the checkers slid off the boards.

After only half a minute, the wind stopped and the contestants began to gather their pieces off the floor. The contestants that had been winning groaned and griped loudly. "This is unfair!"

"Why are they hosting the tournament in such an awful location?" And, in contrast, the contestants who had been on the losing end of the game smiled quietly, for they now had a new chance to win. Only three games had finished before the wind-storm. The winners of those games smiled broadly; they had beaten the disaster.

"Unbelievable," proclaimed King Fredrick. "All those games were lost."

"Bah." declared Marcus. "Inefficient and stupid."

"What can they do? All of those checkerboards crashed to the floor before the games were finished. There was nothing that they could do." Insisted the king.

But, Marcus had stopped listening. Instead, he was wandering down to the nearest competition table.

"Excuse me, there. Why do you make them replay the game?" Marcus asked the judge at that table. "Why not use checkpoints?"

"Checkpoints?" asked King Fredrick, who had followed Marcus down to the floor.

"Yes. Write down the entire state of the board after each move. That way, if the pieces are upset, you can reproduce the entire board from the most recent checkpoint. It would save your games from being lost." explained Marcus.

"HA! Checkpoints?" cried Jennifer "King Me" Stratovarious from behind. "That would be too slow. Have you ever seen how fast I can play checkers?"

Marcus had indeed seen how faster she could play. He had to admit that checkpointing every move could only slow down someone of her caliber. In fact, Marcus was surprised the even a judge could keep up with her.

Marcus grinned widely. "Perhaps I can be of service." he offered. Then, without any more explanation, he picked up the table's timing clock and waved his hands over it. After a moment he set it back down.

King Fredrick looked at the clock. It appeared mostly unchanged, except that it now had two additional buttons "Save" and "Restore".

"May I?" inquired Marcus. Then, without waiting for an answer, he pressed the "save" button. The clock chirped once like a bluejay. Marcus smiled widely at the assembled crowd and, with a quick flick of his hand, knocked the table's board onto the floor. Checkers flew everywhere. The judge and both players scowled at him.

"Now, observe." commanded Marcus with his best wizard's voice. He reached over and pressed the "Restore" button. Magically, all of the pieces flew up off the floor and reassembled themselves on the board. In less than a second, the full state for the board had been restored.

Everyone gasped and burst into applause.

"Woah." King Fredrick said.

Then, Marcus felt a tap on his shoulder. Behind him stood four hundred and ninety-nine other table judges. Each judge held their table's timing clock out toward Marcus and looked at him expectantly. As he took the clock from the nearest judge and started his spell again, Marcus suddenly regretted having felt the need to show off.