Archive for January, 2008

Power Tools

January 22nd, 2008

I subscribe to the Coding Horror RSS feed, and I generally read new posts as soon as they are released.  Today Jeff Atwood writes about ClipX.  I just installed it, and it is a great little tool.  It basically adds a history to your clipboard.  Using CTRL+SHIFT+V shows a history of items placed on the clipboard.  Nice!

ClipX adds functionality that *should* be part of the Windows OS.  Something else that was missing for a long time in Windows was an improved app switcher.  Several months ago I was browsing the Windows Developer Power Tools site and found TaskSwitchXP Pro.  This adds a much improve ALT+TAB functionality to Windows XP.

It is amazing how many little tools are available for Windows.  One would think that Microsoft would do one of the following:

  1. Develop similar functionality and add it to Windows or,
  2. Buy the various tools found on the market and add them to Windows or,
  3. Add these features to Plus! and make a little extra cash, or include them in the free Windows Power Toys.

XML, XSD, and C#

January 21st, 2008

I have really started diving into some of the new XML features of SQL Server.  I know I am a  little late to the game, but I was spending my time learning WPF, WCF, WF, Silverlight, and C# 3.0 (sheesh, Microsoft)!

SQL Server 2005 comes with some cool client-side libraries for using XML in .Net.  One of the things I like is that you can pull and push XML in and out of a command object, and enforce the data schema of the XML with an XSD schema.  Still, working with XML in .Net is a chore and is not strongly typed.  But I just ran across this command:

xsd.exe -c -l:c# -n:namespace schema.xsd

You can find documentation here for the arguments of xsd.exe.

This creates a class or classes for all of the defined elements of the XSD.  To generate classes object instances at runtime, simply use the XmlSerializer!  What I really like about all of this is that xsd.exe generates *partial* classes.  You can then write additional business logic, if needed, for the classes.

Nice.

goto

January 17th, 2008

Remember goto? If you are young enough, you may not. The goto statement does exactly what it says, moving code execution to name position. In one of my first C/C++ classes in college, using a goto statement meant an automatic F for the assignment. This is because goto makes code very hard to read. It is hated for a good reason. Decision statements like if/else and switch are much better choices.

Today I learned a good use of goto that actually make code more readable.

In C#, the switch() statement does not allow case fall-through. Consider the following example in C:

switch(someIntValue)
{
case 1:
printf(“Found case 1!\n”);
case 2:
printf(“Found case 2!\n”);
case 3:
printf(“Found case 3!\n”);
case 4:
printf(“Found case 4!\n”);
break;
}

If someIntValue equals 2, this would print:

Found case 2!
Found case 3!
Found case 4!

In C#, this does not work. The developers of C# chose to not allow fall-through for better code readability or code maintainability. To allow an equivalent functionality in C#, use goto:

switch(someIntValue)
{
case 1:
Console.WriteLine(“Found case 1!\n”);
goto case 2;
case 2:
Console.WriteLine(“Found case 2!\n”);
goto case 3;
case 3:
Console.WriteLine(“Found case 3!\n”);
goto case 4;
case 4:
Console.WriteLine(“Found case 4!\n”);
break;
}

In this example, goto actually makes the code more readable and more maintainable by making the fall-through explicit instead of implicit. I have been programming C# since 2001, and I did not know this existed until today. Very cool.

Mix 08

January 16th, 2008

Mix is Microsoft’s conference on various web-centric technologies such as ASP.Net, AJAX and Silverlight. It is taking place March 5 – 7 in Las Vegas. MS just extended the deadline for the discounted registration until the end of January. I just signed up this weekend for the conference and am really looking forward to the event. I am particularly excited to see Silverlight 2.0. Microsoft will either be releasing GA code, or a late beta for Silverlight 2.0 at the conference, depending on who you believe. I encourage anyone that can get reservations to attend.

And Now, A Word On Baseball Parks

January 4th, 2008

My wife and I are huge baseball fans, and consequently have traveled to a number of parks to watch baseball. Here is my list of parks I have visited in order of how cool I think they are.

  1. Wrigley Field (Chicago Cubs). Wrigley is located on the north side of Chicago, in a neighborhood, and is best traveled to by train. In other words it is scenic, it is easy to find a place to eat or drink before/after the game, and it is easy to fantasize about renting an apartment across the street from the park. Wrigley is the second oldest park in all of Major League Baseball, built in 1914. It is quite simply unequaled, and I doubt a park will ever be built that outdoes Wrigley.
  2. Yankee Stadium (New York Yankees). The Stadium as it is called to many fans of baseball is the house the Ruth built. The aging structure is an experience. From monument park in left field to the boisterous fans, nothing is like Yankee Stadium. Except the new one they are building across the street.
  3. Coors Field (Colorado Rockies). The open feel of this mile-high ballpark make it a real winner. There are pine trees growing in the bullpen, and there is no shortage of cold Coors beer. If you are in Denver during baseball season, make Coors Field a stop!
  4. Rangers Ballpark in Arlington (Texas Rangers). Sitting in Rangers Ballpark on an August afternoon defines Texas heat, but the layout of this park is great. I particularly enjoyed the spacious picnic table seating and very friendly park staff.
  5. Minute Maid Park (Houston Astros). Sitting in air-conditioned Minute Maid Park, there is more a feeling of being at an indoor football game or a basketball game. However the real grass and interesting park features like the sloped outfield make the game fun. The people in Houston are not as nice as the people in Dallas, but they still sing “Deep in the Heart of Texas” between innings, even though Houston is about 50 miles from the coast.
  6. Busche Field (St. Louis Cardinals). I was expecting something better. Busche is comparable in architecture to Arlington or Denver. However, it lacks the open feel of Denver and the amenities of Arlington. Cardinals fans are definitely not as friendly as many of the other locations, with the exception of Yankee Stadium. A nice park, but I probably won’t visit again.

We are hoping to visit several new parks this year.  Fenway is on our short list, and we may try a road trip involving parks on the east coast.  PNC is another one high on our list.

We have also been to three minor league parks. Our favorite of the three (El Paso, Memphis, Round Rock) is Dell Diamond in Round Rock, TX. The Houston Astros AAA “Express” play at this beautiful little park. There is really not a bad seat anywhere, as the park only seats about 12k packed. However the crowds are always good, especially on Fridays and Saturdays. It is usual to see 10k people in attendance on the weekend, and I would get 3k during the week.

Well, that is it!

Exceptions Are A Good Thing, Part 1

January 4th, 2008

I was reading a new post over at Jeff Atwood’s excellent blog Coding Horror today, and the comments section featured some discussions on exceptions and exception handling. I have had more than a few conversations/arguments with fellow programmers about error and exception handling over the years. I am going to attempt to sum up some of my thoughts across a couple of blog posts.

In C# and several, similar languages, the try/catch/finally block is used the trap exceptions.

Try/Catch/Finally Block

The system will throw exceptions for a number of reasons. When working with code that is likely to through an exception you really should try to trap it and do something with it, even if that something is simply to re-throw the exception.

I lump system-generated exceptions into three group:

  1. IO Exceptions.
  2. You’re not using this API correctly exceptions.
  3. Weird Exceptions.

The group “IO Exceptions” means that a network connection, database connection, file connection, etc, was lost or interrupted and an exception is thrown. “You’re not using this API correctly exceptions” mean invalid argument exceptions, use of deprecated code, etc. These exceptions are intended to be caught early, during testing, to inform the programmer that the API is not being used in the way that was intended. “Weird Exceptions” are everything else. I am sure anyone with enough time in the programming world will have encountered truly bizarre, freak situations, with exceptions being thrown in a relatively safe chunk of code.

When writing database, networking or file IO code, the programmer should expect something bad to happen. What happens if the database schema has changed, or the server goes down (or is too busy), or a file is locked by another process? When dealing with anything outside the boundaries of the running process, it is wise to go ahead and assume that an exception will occur and handle it accordingly. I think that this is a pretty solid argument to make; you would have a difficult time coming up with a counter argument that held any water.

How to handle the exception once thrown is another argument altogether. When working with IO Exceptions, a programmer is usually faced with a situation where the program is using valuable resources. If the exception is simply allowed to bubble up unhanded, these resources will not be freed. In the case of a .Net data reader, if a connection is lost to the database and an exception is throw, the try/catch/finally block should make sure that the read is closed and disposed, and that the connection is closed and disposed, if needed. The simplest next step is to just re-throw the error once resources have been cleaned up.

Try/Catch/Finally Block

Another school of thought is to attempt to compensate for the error. I had a co-worker (we let him go) that wrote a while loop to continued to attempt a SOAP XML Web Service call over and over until it succeeded, with no way of escaping the loop. The client code using this poorly written chunk of logic simply waited and waited. This is an extreme case of bad programming, as I am sure you would agree. I have seen similar code that retries for a limited amount of time, then throws the exception, etc.

I don’t like compensating logic in most cases. Or rather, I don’t like it in business or data logic. If an error occurs, higher-level code should do the compensating or simply inform the user that something bad has occurred. Additionally, compensating code can have unintended consequences.
First, compensating code often hides the exception. This is bad news for developers and software tested trying to test the code. Compensating code can also hide bugs that occur in regular intervals, instead of those truly exceptional-case errors (network down, file locked, etc), which is what exception-handling code is supposed to address.

One of the fundamental problems with compensating code is that there is usually only one way to compensate: try again. A very, very bad side effect of compensating code that “tries again” is that it can cause data corruption. Your customer’s data integrity should be your top concern. Code that tries to automate retries of failed calls can end up calling business logic over and over by accident.  Imagine a piece of business logic that subtracts money from an account.  Now imagine it being called over and over, by accident. And compensating code that hides an exception may cause other code to execute that the programmer had not intended to execute in the case of an exception.

To sum up, here is how I handle most “expected” exceptions:

  1. Log that the exception occured.
  2. Clean-up any resources that are in use in the local scope.
  3. Re-throw the exception, or bundle-up the exception in a new exception and throw it.

This pattern is demonstrated in the code block above.  This simple approach does several important things. Please consider the following:

  1. Debugging code at a customer site is difficult. Logging exceptions means that you have (drum-roll) a log file to use to aid in the debugging.
  2. Cleaning up resources limits the impact of the exception. The task being performed may fail, but it won’t create memory leaks, database locks, files locks, or other issues that will result in bigger trouble than that previously-mentioned single task failing.
  3. Re-throwing the error in business or data logic allows higher level, work flow oriented code to compensate for problems, or allows the user to compensate.
  4. Re-throwing exceptions allow developers and testers to find bugs earlier in the software life cycle. With adequate testing, this results in better code getting into the field.

Next time I want to discuss when it is a good idea to create and throw exceptions in your own logic.