Gray's Matter
Justice Gray - North America's Favorite Metrosexual Urban Legend
Starscream and Calgary Code Camp
I wish I was getting to Calgary Code Camp this way

Everyone who is everyone in the Alberta developer community is going to Calgary Code Camp on April 28th.  Everyone except one person, that is - my grandmother.  She was originally hoping to come out and "have a talking to" the "confused young man" who continues to send her flowers and lipstick-covered photographs of himself.  Now that she is out of commission for a while, I guess it is up to me to tell Jeff Perrin in person that she is married and just wants to be friends. 

While my grandmother won't be there, two other industry luminaries will: Donald Belcham and D'Arcy Lussier.  So we'll use these two and their imaginary travel plans as a tribute post to Granny, and at the same time cover off yet another of Scott Hanselman's potential interview questions, this one being:

"What is strong-typing versus weak-typing? Which is preferred? Why?"

We join Donald Belcham at the Edmonton International Airport, awaiting his flight to Calgary.  Since Donald looks like an incredibly shady character, the airport security force orders Donald to fill out a declaration form indicating every single piece of luggage he has, along with its type; otherwise, Donald will not be allowed on the flight.  Donald fills out the form thus:

Drink: 55 cans of Sanpellegrino Limonata
Videotape: Star Wars - Return of The Jedi
Alcohol: 20 L of scotch

sanpellegrino_limonata.jpg
I've seen the inside of Donald's fridge - this situation isn't that unrealistic


As Donald's baggage is inspected, all of his items are checked one by one.  Finding a suspicious item, the airport security stops Donald to tell him that they have found a plush Han Solo doll that he has failed to declare; they cannot allow him entry onto the plane unless he makes another declaration.  Donald refills the form, adding

Marital aid: Han Solo plush doll

to the list.  He tries to go through the airport screening again.  They stop him once more to explain that a Han Solo plush doll is actually a toy and *not* a marital aid, and thus cannot be declared in that fashion.  Donald insists that the Han Solo doll can actually be both.  The airport security tell him that it is illegal to use the Han Solo plush doll as a marital aid on his trip.  He will have to declare it as a toy if he wants to take it on the plane - and if he tries to use it as a marital aid he will be arrested.  After some passionate arguing and crying in the fetal position, Donald's final declaration form looks like this:

Drink: 55 cans of Sanpellegrino Limonata
Videotape: Star Wars - Return of The Jedi
Alcohol: 20 L of scotch
Toy: Han Solo plush doll

Everything now checks out.  Donald Belcham is coming to Calgary, and its women (and livestock) will never be the same.

With Donald safely aboard to sexually harass unsuspecting flight attendants everywhere, let's check in with D'Arcy Lussier.  Unlike Donald, D'Arcy lives in Winnipeg where the concept of modern commercial flight is a science fiction fantasy.  He heads over to farm subcolony #72 to get in the bed of the pick-up truck that will cart him off to Calgary.  Before getting on the "flight", D'Arcy also has to provide a list of his luggage, which is as follows:

Mexican wrestler mask
Picture of John Bristowe
Saved By The Bell, Seasons 3&4

Saved By The Bell Seasons 3 and 4 - featuring the Zack Attack
The DVD that features the Zack Attack, D'Arcy's favorite band

Note here that D'Arcy has not declared any type for these objects.  This is because the Winnipeg Travel Fiduciaries consist of a stuffed moose, a dead squirrel and a sign saying "BE BACK LATER 4 REALZ 1996".   Despite their varying types, D'Arcy plans to use *all* of these items as marital aids, despite the illegality of those acts in Alberta.  As far as the Winnipeg Travel Fiduciaries are concerned, D'Arcy can use his luggage however he likes; however they will not be responsible for protecting him if there is any inappropriate item usage while in Alberta.

The difference between these two situations is coincidentally similar to the difference between strong typing and weak typing!

Donald's airport experience exemplifies strong typing.  In a strong typing situation, the type of all of your variables (Donald's luggage items) must be declared prior to compile time (boarding the aircraft).  If any variables are left undeclared, the compiler (airport security) will flag an error; in our analogy above, this is represented by Donald being denied passage on the aircraft when he did not declare the type of his Han Solo plush doll.  The compiler will also fail if you attempt to use an object in an inappropriate way (when Donald attempted to declare it as a marital aid, when it's really just a toy).  Both of these failures are shown below using C#:

class MaritalAid
{        
}

class Toy
{
}

class HanSoloDoll : Toy
{
  public void PlayWith()
  {
    Console.WriteLine("WHEEE");
  }
}

HanSoloDoll hanDoll = new HanSoloDoll();
// the line below will fail as this object hasn't been declared - compiler doesn't know what type it is.
undeclaredHanDoll.PlayWith() ;
// the line below will fail as a Han Solo doll cannot be used as a marital aid!
MaritalAid m = hanDoll;

D'Arcy's case is an example of weak typing.  In weakly typed languages (Javascript and Ruby, for instance), the compiler doesn't actually care what type your variables are, or what you're trying to do with them - it assumes that you know what you're doing when you're making variable assignments.  The price of this freedom: you'll experience run-time errors if you try to do something with a variable that you shouldn't be.  Using a similar example in Ruby, the following code will compile, but will give run-time errors:

class MaritalAid
   def Use
      puts "Censored"
   end
end

class Toy
   def PlayWith
      puts "Wheeeee"
   end
end

class HanSoloDoll < Toy
end

hanDoll = HanSoloDoll.new();
maritalAid = hanDoll;
maritalAid.PlayWith();  // produces "Wheeeee"

//  this is a run-time failure: Ruby treats this as a basic object, which has no PlayWith method
undeclaredHanDoll.PlayWith();

// another run-time failure - there's no "Use" on the HanSoloDoll or Toy classes, which this evaluates to
maritalAid.Use(); 

Which one of these is better?  I don't believe one is actually better than the other; I think it is a matter of personal preference.  Weak typing is certainly easier on the original developer (easier to compile, at any rate), but it can be much harder on the maintaining developer, since poor development can lead to very convoluted code.  Sure, you can write bad code in *any* language (goodness knows my career is evidence of this fact), but weakly typed languages make it a little bit easier.   This is why test-driven development and unit testing become even *more* important in weakly-typed languages, but that's a topic for another post entirely.   

Do any of you out there have a preference?  If so, what is it and why?  [The Igloo Coder has posted his thoughts on the issue here.]

Previous entries in the "My grandmother and" series:

globe.gif

I thought I would continue my seeming tradition of hitting these questions once every 6 months.   Actually, I had given up on Granny getting into Corillian but that's okay; she's seen the light and is now an independent consultant!  Nonetheless, I have still felt the need to answer some of Scott Hanselman's old interview questions in an attempt to help get her up to speed.

So, without further adieu, let's tell two stories about marriages:

Story #1:

My sister-in-law is getting married this coming May.  I had a chance to meet her future husband's parents this past Christmas, both of whom are from Quebec and primarily speak French.  As is my custom when I am meeting new people, I tried to amp up the patented Justice Gray charm ™ and impress them with the French I vaguely remembered from about a decade and a half ago.  I introduced myself ("Je m'appelle Justice") and then decided to follow up with the coup de grace: terrifically witty banter.  

"The French I am speaking now is the only French I know!"


I paused for laughter - but instead was met with nervous silence!!  In this moment, I finally learned what Donald goes through at the beginning of every EDMUG meeting.

I was definitely a little confused; after all that sentence should have been a guaranteed laugh riot.  My future brother-in-law came up to me and quietly whispered,
"I think I understood what you were saying, but my parents actually think you have some sort of handicap now"

It seems instead of my intended phrase, I had stated something closer to

"I speak French.  French speak!!  Only French!!  I know speak!!!"

Fortunately, I solved the awkwardness that night like anyone would: by getting *completely hammered*.

Speaking of solving all of the world's problems through excessive alcohol consumption , let's go onto story #2.

As most of you know, I was married a year and a half ago.  What many of you don't know is that one of my groomsmen, flush with alcohol and ready to try and impress the ladies, decided to go to one of the bridesmaids and show off his *fluent* knowledge of Cantonese.  Whatever his planned come-on line was will forever remain a mystery.  I wish I could say the same for the translation of what he *did* say, which was, "Boy, I'd really like to sleep with your mother."  

So, what's the problem here?  Lost or unclear intent through translation, or lack thereof.  This is also the difficulty Scott Hanselman was referring to when he asked

"What’s wrong with a line like this? DateTime.Parse(myString);"


This line on its own seems pretty simple - after all, you're just asking for the runtime to take a standard string and convert it into a DateTime object.  

DateTime myDate = DateTime.Parse("10/06/2006");

What's the value for myDate.Month and myDate.Day?

And therein lies the problem: there is no way for you to tell me this without knowing additional information.

For example, if I am running this with an English culture, the DateTime object represents October 6, 2006.  However, if I ran this same line on a computer with its culture set to French (or if the application's culture was set to French), then the DateTime object now represents a completely different date (June 10, 2006, to be precise).  This happens because French dates reverse the position of the month and the day.  

To get around this, always pass Culture information as the second argument to DateTime.Parse, as in the following:

DateTime myDate = DateTime.Parse("10/06/2006", System.Globalization.CultureInfo.GetCulture("fr-FR"));

Now, obviously you wouldn't want to do a culture retrieval every single time you call DAteTime.Parse!  Your application should probably be setting the culture itself, somewhat like the following

System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("fr-FR");
DateTime myDate = DateTime.Parse("10/06/2006", System.Globalization.CultureInfo.CurrentCulture)


This sets the culture for the particular thread of execution that your current user is experiencing.  

You might not think that globalization errors are as embarassing as the two stories I talked about earlier.  Trust me, in the context of a globalized application, they are even worse.  Take this tip and use it to save yourself humiliation in code reviews everywhere!

Previous entries in this series:
My grandmother and the Global Assembly Cache (and Star Wars)
My grandmother and the difference between processes and threads
My grandmother and the difference between HTTP GET and HTTP POST

starwars1.jpg


[This posting series had been on hiatus for a long time, as I assumed knowing the difference between processes and threads as well as distinguishing between HTTP GET and POST would have been enough for my grandmother to squeak by a Corillian interview.  However, it's been a little while and she hasn't gotten any callbacks from Scott Hanselman so I am going to continue with my series based on his previous sets of interview questions.]

So what is the GAC (Global Assembly Cache)?

Let's start with Donald Belcham - EDMUG president, unrepentant alcoholic, collector of restraining orders...and unabashed Star Wars fan.

Donald has a Star Wars party at his house once a month.  You might be wondering why you've never been invited to one of these, and the answer is that no one is invited to these parties except Donald, who proceeds to dress up in costume and practice light-saber swinging ala George Michael Bluth from Arrested Development.

swkid.png
Donald Belcham's Star Wars Party: The early years


The key ingredient to a "successful" Donald Belcham Star Wars Party is the presence of the original Star Wars movie.  Every time he holds his party, Donald goes out and rents a copy of Star Wars.  For many Saturday nights, Donald has watched and cheered alone and drunk in his apartment as Han shoots Greedo in cold blood.  This is what leads him to his frenzied Star Wars Kid style light-saber swinging!  Two hours later, exhausted, he collapses in a drunken heap on the floor, with another Saturday night well spent.

However, Matthew, another erstwhile Star Wars fan, wants to start having a Star Wars party of his own - one with other people attending!  However, seeing as Matthew is only 14 years old, he has only grown up knowing the heavily revised version of Star Wars released in 1997**.   Matthew doesn't want to watch the original version, so he calls the video store every day asking when they will have the new version.  Eventually the video store relents and the revised version is stocked in their store.

The video store's tracking system has a problem, however - adding the new Star Wars version into their system has caused a conflict with the old version - such that the old version has been lost for rental. Anyone thinking they are renting the old version (or in Donald's case, depending on it), is in for a nasty surprise.  

Donald goes home for his monthly Star Wars party and eagerly anticipates the scene that will lead him into a lightsaber swinging frenzy.  However, once seeing Greedo shooting first and Han lamely shooting back, Donald curls into the fetal position and loudly sobs for 2 hours in front of the TV until falling asleep - much like most of his other Saturday nights.

The next day, Donald races to the video store and then begins swearing angrily at the store staff, small children, and a puppy about how they have wrecked his life.  The video store apologizes: there is not way to resolve the conflict such that both the old version and the new version are rentable at the same time.  Either Donald's party fails or Matthew's does.  Donald tells the video store that he will never buy anything from the store again as long as he lives and storms out.

One of the tellers realizes that Donald has spent thousands of dollars over the past 10 years renting the same copy of Star Wars and returning it six days late.  Faced with the loss of their main revenue stream, the store works on fixing its tracking system such that *both* movies are rentable from the outlet.

Quite a while later, Donald passes by the video store to see a sign proclaiming that they now rent *both versions* of Star Wars.  They now exist side-by-side in the tracking system!  Realizing that he can finally stop having his "When Stella Got Her Groove Back" solo parties, Donald rushes into the store to rent his favorite film and reclaim his life.  Now Donald's party resumes without chaos, and Matthew can have his as well!!  Everyone is happy.

leia_bikini.jpg
Princess Leia trying to roll back her system to an earlier version pre-GAC


What I've actually described here is life before and after the Global Assembly Cache (the GAC for short).  Let's go back to life before the GAC first.  Say that we have a program on our machine called "Donald Star Wars Party".  This executable has the following supporting DLLs installed to the C:\StarWars directory, with the last three all being dependent on the first:

StarWars.dll (version 1.0) [has a method called HanShootsFirst()]
HanAndGreedo.dll
LightSaberBattles.dll
DarthVaderIsAFatWhiteGuy.dll
Jabba.dll


Several weeks later, we install a different version of the program called "Matthew Star Wars Party" which puts the following DLLs into the same C:\StarWars directory (note which ones I have bolded):

StarWars.dll (version 2.0) [has a method called HanIsAWussy()]
HanAndGreedo.dll
DarthVaderIsHaydenChristensen.dll
Jabba.dll


Once this program is installed, the "Donald Belcham Star Wars Party" program boots up but then crashes shortly after running.  Why is this?  The HanAndGreedo DLL has a method call to HanShootsFirst() that no longer exists in the new Star Wars DLL, as it has been removed and replaced with HanIsAWussy()*.  Furthermore, we have a problem - even if we had a way to roll back the StarWars.dll file and getting the "Donald Star Wars Party" program working, this just means we end up breaking the "Matthew Star Wars Party" program instead.

Now, let's say that instead of installing their DLLs to the same StarWars directory on the hard drive, these programs instead placed their DLLs in the Global Assembly Cache.  When the second StarWars DLL is installed to the GAC, the GAC looks at the major, minor, build, and revision numbers on the DLL.  Since they are different from the StarWars.dll that is already in the GAC, this file is *also* seemingly placed in the GAC without overwriting the existing version!  Actually, what really happens is that the DLL is placed in a hidden subfolder that is a hash of these numbers.  For all intents and purposes it looks like you've just stuck multiple versions of the assembly in the same directory without overwriting.  This enables both programs to run properly, each targeting their own specific version of the StarWars.dll.

Only a couple more of these and you'll get to meet Scott, Granny!  I promise! 

* You might be thinking that if these DLLs were properly designed, that the methods should likely be in the HanAndGreedo.dll and that the older method would be left in for backwards compatibility without making a change that breaks all older code.  And if you are thinking that, you're miles ahead of a particular ASP.NET web control development company...;)
** While I'm not 14 years old, I've actually never seen the original Star Wars movies, only the 1997 versions.  So I can empathize!

 

Since I'm a little under the weather today, I figured I'd post another one of the Hanselman questions for my granny, who is no doubt concerned for my welfare and thinks I should be back in bed!

Let’s say that my grandmother wants to look for some DVDs at a particular local shop. Now, this shop doesn’t run like any ordinary shop. To see if they have a certain DVD, my grandmother has to write down a list of relevant info on a piece of lined paper. Let’s say she is looking for any movie that starred Gape Kaplan that was made before 1980.

She writes down the following:
Actor = GabeKaplan
DateMade = Before 1980
Ignore = Welcome Back Kotter

and gives this piece of paper to the clerk. The clerk reads this information into a microphone and then the back room goes to work finding all relevant titles.

There are a couple of disadvantages to this approach – the company won’t give my grandmother any more paper to write her criteria on, and the paper itself is limited to around 5 lines. So if my grandmother wants to submit anything in detail, she can’t! Also, unless my grandmother starts writing her orders down in some sort of code, anyone else who is listening can hear what she is looking for – no privacy! She may be okay with looking for DVDs in this manner, but she definitely doesn’t want her orders being public knowledge. Not to mention that all of her contact info will not fit on that piece of paper!  My grandmother complains and because everyone listens to my grandmother, the process for actually ordering DVDs is changed, while the search method remains the same.

So, a week later Suresh comes in and he already knows what he is looking for: “Male Nurses Unchained”, Parts 70 through 75. With the new ordering process, he encloses all of his contact info as well as his order information and credit card number on some paper put into an envelope. When he goes up to the till, he tells them, “Order here” and hands them the envelope. They process his request and a week later he receives the shipment straight to his house.

What my grandmother has done, in terms of the HTTP protocol, is called a GET. A GET puts form values (her search criteria) into the URL string (that lined sheet of paper). GETs are recommend in situations where the interaction is like a question (a read operation, a lookup, or any of Gabe Kaplan’s film escapades). Now, the URL string is limited to 256 characters, sort of like that lined sheet of paper has a limited amount of lines. As well, unless the query string is encrypted that information is publically viewable.

Suresh, on the other hand, has executed a POST, which embeds the form values inside the body of the HTTP request (like Suresh’s envelope was given when he made his request). In addition to being slightly more secure, it’s also capable of being much denser than a GET (all of Suresh’s contact info, etc.) since it doesn’t have to contend with URL limitations. The W3C recommends using POST if

The interaction is more like an order, or
The interaction changes the state of the resource in a way that the user would perceive (e.g., a subscription to a service), or
The user be held accountable for the results of the interaction. [in all cases, like Suresh’s transaction].

Bonus: What is HEAD?


A HEAD request is similar to a GET request except no message body is returned (e.g. my grandmother makes a request for DVDs but gets nothing back). This might sound useless but it’s actually a way to simply test a URL for validity, accessibility, or recent modification.

 

Before I begin, a brief bit of technical background:

A while back, Scott Hanselman posted two sets of questions that he feels are useful when interviewing:

ASP.NET Interview Questions
What Great .NET Developers Ought to Know

As Scott says, "knowing groking these questions may not make you a good or bad developer, but it WILL save you time when problems arise. "  Even if they weren't in some ways instrumental to your development path if you are a .NET developer, the knowledge will still come in handy.

And now a brief bit of *other* background:

My grandmother is part of the readership of this blog(*),but is not necessarily all that technically minded.  She is a wizard at using her DVD player, and I have no doubt that she could pick up any topic if she so chose since she is a brilliant woman; however, she is not a programmer, and thus a discussion of processes vs. threads would fall on deaf ears.  And what if my grandmother wanted to work at Corillian one day?  Would she be able to get through a Scott Hanselman interview? 

That being said, this is the first of a series for my grandmother:

Hanselman Question #01: What is the difference between a thread and a process?

Let’s pretend that we have a nasty gang called the Narayans (no relation to any living beings...honestly), who have overrun the Rockarts neighborhood and are now slowly converting the homes of the Rockarts neighborhood into drug factories.  Having taken over the neighborhood, they also have free access to most of the banks, grocery stores, and other local businesses in the neighborhood.

Each member of the Narayan gang wears the same crusted-over hoodie as a gang symbol.  To tell each member apart, they have a name and number on the back of their hoodie.

The police don’t really care about the Rockarts neighborhood all that much - in fact, they never really liked the Rockarts neighborhood in the first place!!  Thus, they don’t care if it gets run over by the Narayans.  However, to protect the city from gang warfare, they’ve erected a barrier between the Rockarts neighborhood and the next one over, so as to prevent the Narayans and the rival gang, the Fedirkos from having a shoot out.  

Now, the Narayans are a pretty organized gang; they have a detailed report that describes the Rockarts neighborhood and details the plan to convert all the homes into drug dens.  It also has a tally of all of the stores that the Narayans now run, as well as information on every outsider in contact with the Narayan gang and their varying levels of access to different areas of the neighborhood.

You might think being part of the Narayans gives some decent benefits (except for wearing that dirty hoodie) and you’d be right.  Each member gets a storage locker in the neighborhood, and a blackberry that automatically updates with the state of the city as a whole.  Each member operates either overtly or undercover depending on the situation.  Overtly members carry a rocket launcher, while undercover members carry a pen knife.

Now, onto processes and threads.

"Windows Internals" (an excellent book that every developer should read at some point) describes a process as the virtual address space and control information necessary for the execution of a set of thread objects, but you don’t care about stuffy definitions in awesome thought-provoking books!  You care about the Narayans!!  So let’s rewrite this definition in terms of the gang. 

Process: the neighborhood limits (virtual address space) and detailed report (control information) necessary for individual gang members to operate (execution of a set of thread objects).

"Windows Internals" describes a process as containing:

  • A private virtual address space
  • An executable program that is mapped into the process' virtual address space
  • A list of open handles to system resources that are accessible to all threads in the process
  • An access token (a security context that identifies the user, security groups, and privileges associated with the process)
  • A process ID (unique identifier)

Likewise, in our analogy, a process contains:

  • The neighborhood, bounded by its limits (A private virtual address space)
  • The drug den conversion operation (An executable program that is mapped into the process' virtual address space)
  • The tally of all the stores the Narayans now run (A list of open handles to system resources that are accessible to all threads in the process)
  • Information on the outsiders0 [An access token (a security context that identifies the user, security groups, and privileges associated with the process)]
  • The stain-encrusted hoodie [A process ID (unique identifier)]
  • At least one gang member (At least one thread of execution) – after all, how do you have a drug den conversion operation without anyone working towards it?

Now, a thread, on the other hand, is described as being an entity *within* a process that Windows schedules for execution.


Thread:  An entity within a process that Windows schedules for execution (in our case, a Narayan gang member).

A Windows thread includes the following essential components:

  • The contents of a set of CPU registers representing the state of the processor.
  • Two stacks, one for executing in kernel mode and one for executing in user mode
  • A private storage area called thread-localed storage for use by subsystems, run-time libraries and DLLs.
  • A unique identifier called a thread ID.

In our case, reworking this to describe a Narayan gang member:

  • The Blackberry with the city status [The CPU register contents]
  • The grenade launcher and the pen knife [Two stacks, one for executing in kernel mode and one for executing in user mode]
  • The storage locker [A private storage area called thread-localed storage for use by subsystems, run-time libraries and DLLs]
  • The name and number on the back of the hoodie [A unique identifier called a thread ID]

So, a process is actually a larger, more encompassing set of information, of which a thread (or Narayan gang member) is only a part. Threads can only operate within their process and on the space available to their process - they cannot operate on memory that is exclusive to another process (hence, why the Narayans can't operate in the Fedirko gang territory).

Don’t worry, Granny!  One day we’ll get you to that Corillian interview!

 (*) My grandmother does not have a computer; however, she reads this blog by my printing out the entries and passing them along.  I haven’t asked her opinion of the MSDN conference but I know she agrees that Biztalk needed better representation!

Other entries in the "My grandmother and" series: