## Monday, September 26, 2011

### The Marvelous IF-ELSE Life of the King's Turtle

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.

Fido, the King's prized pet turtle, lived a charmed life. He spent his days in the garden fountain, swimming and sleeping. He did not have any magic powers, aside from the ability to amuse himself for an hour by staring at a pebble, but King Fredrick was quite fond of him. The castle's servants took good care of him. They made sure that his fountain was always mostly clean -- Fido did enjoy the occasional patch of slime on the ground.

Fido lived by a series of simple rules. In fact, since his brain was roughly the size of a pebble, they were incredibly simple IF-ELSE style rules. These rules made up Fido's entire daily routine. For example, he had very simple logic to determine when he ate:

IF he is hungry
eat

This logic worked out great for Fido, because he ate when he was hungry. And, as a natural consequence, he did not eat when he was not hungry. It was quite a good system.

For some aspects of life, the IF statement could have two different actions depending on the condition. For example, when he was swimming:

IF the fountain is on
play in the fountain
ELSE
swim around the large rock

Obviously, Fido enjoyed the fountain more than the rock.

Sometimes the decisions would be complex enough to require a series of chained IF-ELSE statements:

IF it is sunny
sit in the grass
ELSE IF it is warm
go swimming
ELSE
sleep

The gardener responsible for taking care of Fido often joked that: "All that turtle does is eat, sleep, and swim", which was not far from the truth. The logic that ruled Fido's life consisted of about fifty different actions contained within chained and nested IF-ELSE statements.

A scholar had once spent a week studying Fido, and he had managed to record the entire logic for Fido's routine on a single scroll of parchment. If Fido had been intelligent enough to understand what that meant, he might have been offended. Instead, he sat in the grass -- it was sunny.

Then, one day, the unthinkable happened. The gardener decided that Fido was probably getting bored, so he added a SECOND large rock. This addition threw off Fido's IF-ELSE based routine completely. It took almost a full week for Fido to come up with a new routine that suited his new environment. In the end, he added another IF-ELSE:

IF he is closer to the right rock
swim around the right rock
ELSE
swim around the left rock

Thus order was restored to his life.

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

For more discussion of IF-ELSE also see Learning IF-ELSE the Hard Way.

## 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."

"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 ==).

## 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.

"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."

"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.

"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.

## Tuesday, September 6, 2011

### Integer Overflow and 00000 Customers Served

Integer data types store values that are mathematical integers. Depending on the programming language and the exact data type, the amount of storage space allocated for an integer can differ. The space directly determines the maximum number of values that can be stored in the variable, and thus the highest value that can be represented. For example, an unsigned 16 bit integer can store 2^16 = 65536 different values-- the numbers 0 to 65535. In some programming languages, assigning a value outside this range will cause the value to "wrap around". Luckily, most modern program languages allow 64 bit integers, providing an upper bound that will match almost every possible use case.

"I like the sign." declared Zed. It was his first visit back to the castle and his pilot store since he had left the coffee business to speculate in coconut sales.

While the new management had resisted making any radical changes to Zed's Coffee shop, they had insisted on a flashy new sign. The sign was at least six feet wide and stood fifteen feet above the ground. It was lit by ten different torches around the base so that it could continue to attract in patrons at night. Some people had claimed that this sign represented the future of coffee advertising.

However, one thing about the sign bothered Zed: the message saying "02053 Served". It reminded him of a problem that he had once encountered with the coffee shop. So he had decided to ask the new manager about it.

"How do you update the sign?" inquired Zed.

"It is pretty simple." answered the manager proudly. "Each digit is a different card. Every morning Rob, over there, climbs up a ladder and changes the digits to reflect the previous night's count. He has to pull down the old cards and put up new ones."

Zed nodded politely. He was, of course, familiar with the principle. Anyone who had been in the coffee industry would know how such a sign worked. He was simply warming up to his real question.

"So, you have five digits -- zero through nine." confirmed Zed. "But what happens when you rollover?"

"Yes." replied Zed. "What happens after you serve customer 99,999?"

The manager looked shocked. "We... Well... I... I never thought of that." he answered.

"Ah." responded Zed knowingly. He had considered the same board a few years ago, but his experience with the coffee menu board had taught him to be wary of a fixed number of slots. Specifically, a fixed number of digits limited the maximum number that could be displayed. And, in this case, five digits was absurdly small for a successful coffee chain.

When Zed left, ten minutes later, the coffee shop's manager was still on the phone with the sign company. Zed could hear the manager shout: "I can't just let it overflow. Do you know how bad it would look to have it wrap around to say '00000 served'?"

Zed smiled to himself. While coconut speculation did not have the same level of excitement as coffee shops, sometimes that was a good thing.

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

## 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.