Author: Pete

Rant

Y Kant Developers Read?

Bookshelf image from flickr.com/photos/ianturton/2341264331/
I guess there are two major reasons that developers don’t read many books. This is kind of a timely subject for me right now on both fronts.

First, I began a new job at the beginning of last month. My new employer was running a Visual Fox Pro environment and wants to move to a full-blown .Net SOA Architecture. I was brought in to architect that. The team that I have (save one programmer that I recommended and was hired) are all Visual Fox Pro 6 developers who don’t know a stitch of .Net. With the exception of one guy (who I *really* appreciate), none of them seem to be very interested in reading books to find the answers to problems or to learn the gist of C# and ASP.Net.

This was also the case at my last job. With the exception of the guy who I recommended at my new place, no one would read books. They would take them at our insistence and then never read them. Someone once told me that developers read about one technical book a year on average. I couldn’t believe it when I heard it, but I’m starting to wonder if that number isn’t smaller. The first major reason just seems to be laziness and/or apathy.

The second major reason seems to be the driving force behind Jeff Atwood and Joel Spolsky‘s new venture, StackOverflow. According to Joel, “Programmers seem to have stopped reading books. The market for books on programming topics is minuscule compared to the number of working programmers. Instead, they happily program away, using trial-and-error. When they can’t figure something out, they type a question into Google.”

I believe that to certainly be true, and for people who are using new technologies or are on the bleeding edge, trial-and-error is the only way to go. However, if we are talking about anything that is approaching a year old, books certainly exist. My problem with trial-and-error and Google is that you never really *learn* anything. You are kind of limited to your own cleverness.

Advanced books not only teach you new features, they teach you new techniques. If you just trial-and-error, you will only try to figure out the Python way to do your C# code, or the Ruby way to do what you’ve always done in Java. You won’t learn what there is to learn about the new languages and the cultural mindset that comes with them. You could skip reading books and read lots and lots of source code, but I don’t believe a majority of developers are doing that, either.

However, so far we’ve only talked about learning a new programming language or technology. There is no way to effectively trial-and-error the kind of knowledge that you get from books like Code Complete, Pragmatic Programmer, GOF Design Patterns, or Practical Cryptography. How in the world has this style of learning, proven effective for centuries, fallen so far by the wayside? I am not trying to seem terribly elite, but I really read more than an entire technical book per month on average, along with several technical magazines and journals. I directly attribute my success in my field to that fact. Why can’t people see books as an avenue to their greater success?

Fluff

Great Quote From K

“Everyone knows that debugging is twice as hard as writing a program in the first place. So if you’re as clever as you can be when you write it, how will you ever debug it?”
     – Brian Kernighan (the K of the essential K&R C book)

Code Tips

Anonymous Types in C# 3.0

For a long time, the var keyword has been the domain of only wholly dynamically typed languages. In fact, some people from the strongly-typed camp have considered the use of var as “hacky”, even though C#-ians have been able to treat everything as an object all along. Granted, it is not exactly the same and there is the whole boxing and unboxing thing to deal with, but I wanted to include full disclosure.

Now however, dynamic languages are all the rage and people are finding good uses for a generic variable type. To harness that power, one of the things done in C# 3.0 was the creation of Anonymous Types. Examine the code below and its output.

var blogPost = new
{
    Name = "Anonymous Types in C# 3.0",
    Author = "Pete Shearer",
    Category = "Code Tips"
}; 

Console.WriteLine(blogPost.Name);
Console.WriteLine(blogPost.Author);
Console.WriteLine(blogPost.Category);

Anonymous Types Output

By declaring my variable blogPost with the var keyword, I have created a dynamic variable. Now, after the new keyword and inside the curly braces, I declare a few properties and set their values. Behind the scenes, the compiler has declared a new object, given it a temporary name, and set the values in “traditional” fashion. It is even smart enough that if I declared another var with that definition, it wouldn’t redefine the anonymous type.

Within the anonymous type, the object remains strongly typed. Consider the following alteration to the code:

var blogPost = new
{
    Name = "Anonymous Types in C# 3.0",
    Author = "Pete Shearer",
    Category = "Code Tips",
    Date = new DateTime(2008, 3, 27)
}; 

Console.WriteLine(blogPost.Date.GetType());

Anonymous Types Output 2

The compiler inferred the type from the object placed into it. I know that I said new DateTime there, but it would have worked for any type that I put into that property. This new feature certainly affords developers a new level of flexibility. Enjoy.

Fluff

Why Do You Write Code?

Jeff Blankenburg posed an interesting question on his blog the other day. He asked, “Why do you write code?”. I started thinking about that question and decided that I not only wanted to answer that question on my blog, but that the answer to that question itself would provide a good synopsis about me for my readers.

The short answer is that it is really who I am. I’ve been fascinated with computers and technology for as long as I can remember. We got an Intellivision when I was very young and had the computer add-on when I was in kindergarten. I remember being able to pull sprites from the game cartridges and move them around the screen and writing rudimentary BASIC programs. The system had so little RAM that it had to have a modified version of BASIC; PRINT became PRIN to save a few bites.

I remember being enamored with what that computer represented. I could give instructions to a machine and it would do as I had asked. I loved programming on the computer because it shared two major themes with another love of my life, Mathematics. First of all, programming was about solving problems. I am at point A, I need to get to point B, what steps can I employ to make that happen? Secondly, computer programming was exact. Barring weirdness, a computer executed its instructions the same way given the same inputs the same way that 2 + 2 will always equal 4. There is something comforting in that.

After the Intellivision computer, we got a Commodore 64 and then a Commodore 128. Games Magazine used to publish BASIC programs for you to input into your computer. There were a lot of PEEK and POKE commands in the lines of code that I didn’t understand at the time, but I still felt like the world’s biggest hacker to make this code run.

As I grew up, I went through a variety of languages and ultimately ended up where I am now, writing C#.Net code. The platforms and the languages have changed, but what I do is still about taking a challenge and performing steps against it in order to reach my goal. 2 + 2 still always equals 4, though sometimes I really have to pay attention to make sure that the computer is getting 2 and 2 and not -87 and 1,348,849 😉 The computer isn’t very smart and does only exactly what it is told, which I guess sometimes makes me not very smart!

Even with that limitation, I feel extremely fortunate to have a career I love that remains challenging and fulfilling. There is nothing like the feeling when you’ve been given a difficult task and you are able to overcome it. That’s why I write code.

Code Tips

C# Extension Methods

One of my favorite features of C# 3.0 is the extension method. An extension method basically allows you to add a method to a class without altering the class itself. All you need to do is declare some static methods with a “this” keyword in the parameters. .Net will then add this method on to whatever class you indicate is a parameter of the method (immediately following the “this” keyword). Then, as long as you have included the namespace in your using declarations in the code file, you are all set. Some examples would probably help. Here are some sample declarations.

public static class MyExtensions
{
    /// <summary>
    /// Validates (poorly) if an email address is in
    /// the right format.
    /// </summary>
    /// <param name="address">The email address to validate</param>
    /// <returns></returns>
    public static bool IsEmailAddress(this string address)
    {
        // Note: A purposely short pattern.  Not suitable
        // for enterprise-level validation
        Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
        return regex.IsMatch(address);
    } 

    /// <summary>
    /// Determines the future datetime, given the number
    /// of minutes to go forward.
    /// </summary>
    /// <param name="minutes">Number of Minutes to Add</param>
    /// <returns></returns>
    public static DateTime MinutesFromNow(this int minutes)
    {
        return System.DateTime.Now.AddMinutes(minutes);
    } 

    /// <summary>
    /// Reverses the characters in a string. 
    /// This method should have been included in the base library.
    /// </summary>
    /// <param name="input">The string to be reversed</param>
    /// <returns></returns>
    public static string Reverse(this string input)
    {
        char[] inputArray = input.ToCharArray();
        Array.Reverse(inputArray);
        return new string(inputArray);
    }
}

You can see that I’ve created three methods and added XML comments to them (so I get intellisense on those methods later). Looking at the Reverse method, I declare it just like a normal method, “public static string Reverse” but then in the arguments, I just add a “this” before I set the parameter. So, instead of just “string input”, I have “this string input”. This tells .Net to add this method as an extension on the string class.

You can see from this example that I see my Reverse method in a string’s intellisense as well as my comments for the method.
Example of the Reverse() extension method

My total code to use each of my extension methods listed above is as follows.

static void Main()
{
    Console.WriteLine("Reversed String: {0}", "PeteOnSoftwareRules!".Reverse());
    Console.WriteLine("Now: {0}", System.DateTime.Now);
    Console.WriteLine("In 20 Mins: {0}", 20.MinutesFromNow());
    Console.WriteLine("president@whitehouse.gov: {0}", "president@whitehouse.gov".IsEmailAddress());
    Console.WriteLine("NotAnEmailAddress: {0}", "NotAnEmailAddress".IsEmailAddress());
}

When I run the code, I get the following results.
Example of the extension methods' output.

Good so far, but for now it seems like I am just changing how you would write some validation methods. Instead of IsEmailAddress(“a@b.com”), I am suggesting you write “a@b.com”.IsEmailAddress(). That is true so far. You could also create your own type that inherits from string and add a method, but then everyone else would have to use your type instead of the built-in .Net type. That’s not good at all. Additionally, extension methods add value by solving another problem.

Sometimes, you have to work with a framework or some third party class that has been sealed. I have for you the following example. It isn’t super useful, but concise, and will show my point 😉

public sealed class CannotInheritAndExtend
{
    public string FirstName = string.Empty;
    public string LastName = string.Empty; 

    public void PrintFirstName()
    {
        Console.WriteLine("First Name: {0}", this.FirstName);
    }
}

I really need this class to write out the last name, also. With this example, it is impossible to say “public class WillInheritAndExtend : CannotInheritAndExtend” and then just add my own method. Go ahead and try. You will get a beautiful compiler error. What you can do, however, is the following:

public static void PrintLastName(this CannotInheritAndExtend input)
 {
    Console.WriteLine("Last Name: {0}", input.LastName);
 }

Now my method is included in intellisense for the original class.
Intellisense for the new method on the sealed class.

So, now I can have this code

CannotInheritAndExtend a = new CannotInheritAndExtend();
a.FirstName = "pete";
a.LastName = "shearer";
a.PrintFirstName();
a.PrintLastName();

that produces the desired output.
Results of new method on the sealed class.

As you can see, extension methods are really very helpful. They allow you to keep original types intact, but extend functionality onto them. I hope you find them as useful and cool as I do.