Tuesday, February 24, 2015

...Finally


One of the most powerful, but misused logical constructs in programming is the exception. Exceptions provide the programmer with an exit strategy in the event of a runtime error. Any section of code that could fail should be wrapped in a "try" block. If an error occurs within that "try" block then an exception is thrown and any code in the subsequent "catch" block will get executed. Conveniently, in most languages that support exception handling, the reason for the failure is also passed into the "catch" block. This allows the programmer to check why the failure occurred and handle it appropriately.
Unfortunately, more often than not, programmers either simply ignore the exception and move on or pass the exception on to the user and exit the program. You will see this on far too many websites. No user should ever be exposed to an exception. In my mind, displaying an exception to a user is the programming equivalent of dropping one's pants.
Most programming languages that support exception handling offer a third optional code block known as "finally". The "finally" code block is always executed after the completion of the "try" or "catch" blocks. I have seen far too much code in my career that contains no "finally" block, but does contain duplicate code in both the "try" and "catch". In extreme cases I have seen complex code within the "catch" block that is highly likely to throw its own exceptions under certain circumstances. Any code within the "catch" block should be as simple as possible.
Consider the following ASP.Net C# console application. This application accepts commmand-line arguments and displays them back to the user. A common command-line structure accepts arguments that begin with a dash character ("-") as options with parameters immediately following. For example, "hello -name Brad" would tell the "hello" application to accept a "name" parameter with the value of "Brad". For web developers this is similar to the querystring.
A console program consumes the arguments in a globally scoped array called "args":


 static void Main(string[] args)


In this intentionally buggy example, we echo back the arguments to the user. If the user passes "-name Brad LiveResponse -color Red" then the program will echo:

 Total number of command line argument values: 5
 Arguments...
  name=Brad
  LiveResponse
  color=Red


But if the user passes "-name Brad LiveResponse -color" then the program will fail with the following output:

 Total number of command line argument values: 4
 Arguments...
  name=Brad
  LiveResponse
 Exception: Index was outside the bounds of the array.


The exception occurs due to the following bad logic:

 for (int i = 0; i < args.Length; i++)
 {
  if (args[i][0] == '-')
  {
   Console.WriteLine("\t" + args[i].Substring(1) + "=" + args[++i]);
  }
  else
  {
   Console.WriteLine("\t" + args[i]);
  }
 }


In this logic we assume that when an argument that begins with a dash character is provided then the user will always be kind and provide a value after it. But if the user passes "-name Brad LiveResponse -color" the line "Console.WriteLine("\t" + args[i].Substring(1) + "=" + args[++i]);" will cause a runtime error as it will be incrementing the loop counter "i" beyond the end of the "args" array expecting a value for the color parameter.
So now we have a program with a runtime error that is easy to produce. Why did I choose to demonstrate this with a console application? Any time you run a console application from the debugger it will simply exit when it is done. A program like this runs so quickly that you may never see it execute. In order to see the program execute you will need to insert logic that causes the program to wait before closing. In this example I added:

 Console.ReadLine();


This forces the program to wait until the user hits the enter key, allowing us to see the output. In this example we will always want to run this line before the program exits whether an exception occurs or not. This is where the "finally" block comes into play. If you were to put that line within the "try" block it will get executed only if there is no error:

 for (int i = 0; i < args.Length; i++)
 {
  if (args[i][0] == '-')
  {
   Console.WriteLine("\t" + args[i].Substring(1) + "=" + args[++i]);
  }
  else
  {
   Console.WriteLine("\t" + args[i]);
  }
 }
 Console.ReadLine();


You could put it inside both the "try" and "catch" blocks:

 Console.WriteLine("Exception: " + ex.Message);
 Console.ReadLine();


But if you do that then you've added the same line of code in two different places. This introduces additional maintenance and quality risk if you ever want to change the "end of program" wait action to something else. Instead, add a "finally" block after the catch. This block of code will get executed whether an exception occurs or not:

 finally
 {
  Console.ReadLine();
 }


Note that the "finally" block will still get executed even if the code in the "try" or "catch" block returns to the calling operation before completion.
Consider another example of an application that opens connections to a database. These connections must be closed. By placing the close methods within your "finally" block you can ensure that the connections don't remain open in the event of an error.
The "finally" block allows you to simplify your program by placing any actions together that must get executed every time, whether there is an error or not.

The whole example program follows. If you would like to see it in action, create a C# console application in Visual Studio and replace the program code with this. I intentionally wrote this program with an error in it. Try it out.
  • Run it with a variety of command-line options and see how many ways you can break it.
  • Move the "Console.Readline();" statement into the "try" or "catch" block to see what happens.
  • Add a "throw" statement into your "try" or "catch" to see what happens (hint: a "throw" in the "catch" block produces very interesting results).
  • And, for fun, see if you can write a more robust and terse command-line parser and post it in the comments below.
  • 
     using System;
    
     class Program
     {
      static void Main(string[] args)
      {
       try
       {
        Console.WriteLine("Count: {0}\r\nArguments...", args.Length);
        for (int i = 0; i < args.Length; i++)
        {
         if (args[i][0] == '-')
         {
          //If the argument begins with a dash, include its parameter
          // in the output.
          //If the last argument begins with a dash this line will
          // throw an exception.
          Console.WriteLine("\t"+args[i].Substring(1)+"="+args[++i]);
         }
         else
         {
          //Otherwise just write the argument
          Console.WriteLine("\t" + args[i]);
         }
        }
       }
       catch (Exception ex)
       {
        //The above code with throw an exception
        // if the last argument begins with a dash.
        Console.WriteLine("Exception: " + ex.Message);
       }
       finally
       {
        //Whether an exception is thrown or not this line is
        // always executed.
        Console.ReadLine();
       }
      }
     }
    
    
    

Saturday, October 11, 2014

A Scout is Prepared

Six Weeks

In June of 2013, I dropped my son off at the Spanish Peaks Scout Reservation. He'd signed up to be a counselor in training and would be spending six weeks on the side of a Colorado Mountain. I was nervous. He was only 14 at the time and had never been away from home for more than 10 days before. Not only would he be away from home, he would be a 12 hour drive from home. I had planned for this and was ready to catch a flight to nearby Pueblo and get to him if there happened to be an emergency.

Ready for This

I was confident in his ability to handle an emergency. He'd been trained in all of the scouting basics, and had earned a variety of readiness merit badges. But he'd never faced a real emergency before, and I hated the idea that he might have to face one without my help.

Fires

This particular summer had been a dry one in Colorado and there had already been a dozen or more
major forest fires in the state. Near Colorado Springs, the Black Forest Fire was still burning. But there hadn't been any fires in southern Colorado - yet.

Fire!

Then my fears were realized. On the evening of June 19th I received a call from an unknown number. Normally I let those go to voicemail, but I decided I'd answer this one. Unfortunately I was too late and the call went to voicemail anyway. Once I got to the voicemail I heard my son say "I'm alright, but please, please call me back as soon as you can." While listening to the voicemail I received a text from my wife, "Please call me as soon as you can." Obviously something very wrong was happening. I still hadn't connected the dots to the forest fires. They were all so far away. I was wrong.

Relief

I was able to connect with my son within a few minutes and was so incredibly relieved to hear his voice on the other end. He and the rest of the occupants of his camp had evacuated to a nearby high school where the red cross had set up an aid station. His camp and the mountain it occupied were burning.

Getting There

When I received the call I was out of town on business with a return flight through Denver early the next morning. We made a number of possible plans that depended on where he might be by morning. The fire was out of control and they didn't even know if the town they had evacuated to would be there by the time I could get to him. The next morning I arrived at the Denver airport. We had planned for me to complete my flight home and get him onto a flight home from Pueblo when my son reminded my wife that there were others from our home town that we needed to help. After a very brief discussion with my wife over the phone and the flight attendant at the door I was off the plane and headed for the rental car counters.

No Luck

Not a single rental car was available. I was stuck a four hour drive from my son and had no way to get to him. Then I remembered that a friend lived in Colorado Springs. "What are you doing for lunch?", I asked him. After a little explanation on my part my friend was in the car, heading for Denver. He was able to get me to Colorado Springs where I was able to rent a car. Two hours later I was in Pueblo on the phone with my son, and one hour after that I met him at the high school he had slept in the night before.

45 Minutes

I picked up my son and three others from our area. Thanks to my son's selflessness I was able to get them all lunch and then get them clothes at a nearby department store. They had nothing but what they had been wearing when smoke was first seen. Under normal circumstances it takes 45 minutes to drive from the camp to the nearest town. These had not been normal circumstances. Nearly 200 adults and scouts, some as young as ten years old only had 45 minutes to gather, get into cars, and get off of the mountain before the camp was engulfed. There was no time to go get anything. Some of the tents, my son's included, were already burning by the time everyone gathered to evacuate.

Prepared

But the campers and staff were prepared. They had planned for this and practiced. Every camper and staff member was accounted for and evacuated with only very minor injuries. Those responsible for others, including my son, stepped up an did their jobs to get everyone out safely. The Boy Scout motto is "Be Prepared." Every scout says that. Every scout learns the skills required to handle emergencies. Most never have to use those skills or live that motto. Some do. My son and the rest of the campers and staff at Spanish Peaks Scout Reservation relied on their training and he lived up to the motto.

Next Summer

Only days after picking up my son and the others, those that he selflessly reminded me needed to be helped as well, my son told me that he wanted to go back for the next summer. I wasn't too sure about it, but he was. When I dropped him off for the 2014 session we stood at the spot where his tent had been. It was sobering to see the ashes, but I knew as we stood there that he had gone to camp the summer before a boy and came home a young man. I've never had to directly face the challenges that he had in 2013 and hope I never will. My son faced them and handled them with a maturity that most of us will never have. He was prepared. I know now that he is prepared for the life he has ahead of him and I'm ready to see him face it head on.

References

Our Personal Story of the East Peak Fire
Wikipedia Article About the East Peak Fire

Wednesday, September 17, 2014

A Good Developer is a Lazy Developer

A Good Developer is a Lazy Developer


What!?!? You're kidding, right?

Sometimes I work long hours. Late nights, early mornings. I even keep a notepad handy in case I get an idea in the middle of the night. I've solved many problems at 3am. So why would I make such a ludicris statement as "A good developer is a lazy developer"?

Because it's true.

Over the years I have seen dozens of frameworks, processes, architectures, patterns, etc. all designed to make my life easier. Why would so much work go into making my life easier? Because we are all sick and tired of rewriting the same sort or filter or query over and over again.

Software development has gone on long enough that, except in very special cases, what we're writing has already been written. What we're trying to do has already been done. And what we stay up late at night trying to figure out is only a web-search away, if only we could figure out the right search to get us to it.

Imagine trying to sort a list. All of us programmers have done it. We had to sort a list to pass that horrible CS class, didn't we? We don't ever have to do that again. Every way you can imagine sorting a list is already out there. If you use ASP.Net you can sort any list with one line of code and a delegate method (see a future post on this blog for more on delegates). The delegate method itself is almost always going to consist of one line as well; a simple compare statement. If you write more than that, you are not lazy enough.

How about dates. Oh...I used to hate dealing with formatting dates. Everyone wants their dates displayed differently. And don't get me started with localizing dates. US dates have the month first, everyone else puts the day first. What a mess! Not really. In ASP.Net it is easy. Using a combination of the String.Format methods and the System.Globalization namespace you can get your dates into the format you want with little extra effort. This namespace will also get those commas and periods in your numbers formatted for the right locale with no sweat at all.

Get Lazy!

Learn the API's.

Use the libraries.

References

System.Globalization
String.Format

Thursday, September 11, 2014

Starting Over

It's time I start aggregating all of my various blog posts from around the net. I blog about a number of topics from art and music, to technology, and even stories and odd topics from time-to-time. I'll start with a re-post of a blog entry I posted in July about Quick Draw on Hulu. The post is a little dated now since Dodge City Days is over for 2014, but I have added an update to the end so be sure to read to the bottom.

Dodge City

Originally Published 7/27/14

Growing up in Kansas I never gave travelling to Dodge City a second thought. I couldn't picture it being much more than the dozens of other intersection towns I'd gone through too many times already. So I never went.

Recently, my travels have taken me directly through Dodge City as an ideal stopping point. I wish I had gone before. A city of just over 27,000 residents, Dodge is bigger than most small towns and certainly earns the title of "City".

While other small towns have retained their town squares, Dodge City has gone one step further and retained a small piece of the true Wild West. When you visit you can spend the day exploring the Boot Hill Museum and Front Street experience. This single-block replica of an old west town draws you in and takes you back over 100 years into our western past.

Only a few blocks away, Amtrak still features a rail depot and Santa Fe museum that completes the experience. Riding in from Chicago or Los Angeles is easy aboard The Southwest Chief - an old Santa Fe line that Amtrak continues to run today.

Thanks to these attractions, Dodge City supports an abnormally high number of hotels so you won't have any trouble finding lodging. Unless, of course, you intend to enjoy Dodge City Days - a one-week carnival of events held during the last week of July every year. During Dodge City Days more than 100,000 visitors descend on Dodge City for rodeos, concerts, parades, historic recreations and many other activities.

In 2014, over the last weekend of Dodge City Days a very special event is planned. In an historic recreation of a traditional cattle drive, the city plans to break a record. Guinness will be observing as an attempt will be made to host the largest cattle drive down a main street. Celebrity Marshalls will be on hand including John Lehr and Nancy Hower - co-creators of the Hulu Original series, Quick Draw. Join them as they help kick off the record-breaking cattle drive. Don't miss season 2 of Quick Draw starting on August 7th on Hulu. If you haven't seen season 1 yet it is a must-see.

Intersection Town

I feel that I should explain a term that I used in the article above. Intersection Towns is a term I use for the many, many towns that have two highways intersecting near the center of town and might or might not have a single traffic light. I don't have anything against intersection towns. In fact, I'm quite fond of the many county seats that still have a town square around their courthouse.

Great Bend, KS c.2014
Visit some of these towns - the character and charm is something quite wonderful. Great Bend, Kansas (the town depicted in Quick Draw) is, in fact, much more than an intersection town today, but still has a beautiful courthouse building in the center of a picturesque town square. Visit there if you get the chance - you'll be glad you took the time to stop and look around.

If you can't get to Great Bend or Dodge City look on a map, find the nearest small-town county seat and take a drive. It's worth a day-trip and a nice lunch somewhere you've never been before.

Update

As of today (9/11/2014), the seventh episode of season 2 has gone live. I can't say that it's "aired" since that terminology really doesn't apply anymore. What a joy it is to see John Lehr and the rest of the cast goof it up in fictional 19th century Kansas. The tidbits of real history, unpredictable improv comedy, and fairly adult humor makes me belly-laugh over and over again.

But what makes Quick Draw just a little different than the rest of the historical fiction out there is the way that they mix in the ordinary. Episode 7 features a shoot-out that has got to be closer to the real thing than any other western has ever depicted. The characters spend more time talking to each other and reloading than actually shooting. That tiny addition of realism adds so much to the humor. Try out Terry Gilliam's Jabberwocky for another look at the "what it must have really been like" humor and you'll see what I mean.

Oh, and if anyone is counting. The shootout in season 2, episode 7 just took the top spot away from the duel in season 1, episode 7. I won't use any Harvard Math on you, but I bet season 2 will have a few more episodes than season 1.

Links