Brendan Enrick

Daily Software Development

Visual Studio 2010 Beta 2 is Here

As of today Visual Studio Beta 2 is available to the general public. There is a VS 2010 Beta 2 iso available for download. It has some really nifty features. I’ve been playing around with it.

First off I will say that it actually looks very cool.

StartPage

I think they did well. The new start page here is also a lot cleaner. I’ll be looking to see how to customize it a little.

Creating new projects is a lot better. Far less intimidating in this new default view. If they can keep the clutter down on this I will be very happy.

NewProject

So I created an “Empty ASP.NET Web Application”. I noticed one crazy thing about it. I don’t think there are enough references here? Maybe we need more. C’mon guys. Seriously. Who wants to start with all of these in there? I chose the “Empty” one so I wouldn’t have all of this clutter.

StandardReferences

But wait! They did remove the clutter. Guthrie had mentioned they were doing this. I am just now seeing the web.config and it is AWESOME!

DefaultWebConfig

There is barely anything in the web.config. Yipee! Hooray!

“Navigate To” is a nice feature. I already use ReSharper, so the wow factor is gone. I am glad to have it integrated though.

NavigateTo

We were able to move the editor window around in previous versions of Visual Studio, but this feels a lot nicer, and anyway it’s still useful. Grab an editor window and decide where to put it. Much more freedom for splitting the screen this way.

 

MoveEditorWindow

You can do stuff like this. And have three editors open at once (you better have a lot of screen real estate before you try this).

TiledWindows

Or if you actually use the designer in Visual Studio you can split it along with the code behind file. Getting you the Design, Source, and Code Behind.

TileWithSplitView

This looks like a pretty nice thing they’ve build here. I figured with the big changes they were making that this version of VS would be lacking in too many upgrades. It seems they’ve managed to pull off some nice stuff here.

I am sure I’ll discover more new stuff at some point. Luckily the same feel is here, so just need to learn all of the little changes and additions.

When Should You Comment Your Code

Comment your code when it is hard to understand or determine your intent, because your code is crap. Yep, that is pretty much the best time to comment your code. When I was in college I was told to make sure that I commented my code. I always wondered why. Now I know. Comments really tended to clutter things and make it less clear what I was trying to achieve. I’ve written plenty of comments, but I know that when I use a comment that it means my code sucks.

Comments take time to write, they take up valuable space, they add clutter, and they’re often out of date. So why do we write them? We write them because there is something confusing about some code. Or something that we need to tell future readers about the code.

I very much enjoy being reassured of the way I do things by the books I read. I’ve been reading Code Complete, and it makes me glad they I blatantly disagreed with the people who told me to comment my code. Why? Because the author of the book tells me the exact opposite. I’ve often used the phrase, “code should be self-documenting.” I am not sure from whom or from where I first heard that, but it also affirmed my belief about comments.

The proper use of comments is to compensate for our failure to express ourself in code. Note that I used the word failure. I meant it. Comments are always failures. We must have them because we cannot always figure out how to express ourselves without them, but their use is not a cause for celebration.

Aside from the misuse of the English language, that is an excellent paragraph. I’ve never liked writing comments, and I doubt I ever will. It is interesting how some programmers swear by them. I think they are the same programmers who use single-letter variables, magic numbers, and hundred line methods.

I highly recommend reading through the best comments in source code question on StackOverflow.

Remember kids, anytime you feel the need to write a comment, fix your code instead. You’ll thank yourself down the road. You might be the future developer maintaining the code.

A few steps to follow. (These are the easy ones. Harder ones take more than a bullet point to explain and justify.)

  • Rename variables to more expressive names.
  • Extract methods so people know what you’re doing.
  • Extract classes to handle each responsibility.

Null Reference Exception on Instance Methods

Recently I was reading through a bunch of interesting blog posts. I was looking for information about the use of callvirt in C#. Callvirt can be used to call both virtual and non-virtual methods, and in fact is how all methods are called in C#. I don’t know how much of a performance decrease there is based on this, but I doubt it is much of one. I stumbled across this interesting post covering why C# uses callvirt from Eric Gunnerson’s blog.

We had gotten a report from somebody (likely one of the .NET groups using C# (thought it wasn't yet named C# at that time)) who had written code that called a method on a null pointer, but they didn’t get an exception because the method didn’t access any fields (ie “this” was null, but nothing in the method used it). That method then called another method which did use the this point and threw an exception, and a bit of head-scratching ensued. After they figured it out, they sent us a note about it.

We thought that being able to call a method on a null instance was a bit weird. Peter Golde did some testing to see what the perf impact was of always using callvirt, and it was small enough that we decided to make the change.

Now that certainly is odd behavior. I don’t know how I feel about it though. So basically one could have been able to call instance methods on null instances of an object as long as they didn’t access any members of the object itself. First I will say that methods with fewer dependencies are great.

So C# was of course adjusted to disallow this, but if it hadn’t then this could potentially work.

using System;
namespace NullInstanceMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            Enrick brendan = null;
 
            Console.WriteLine(brendan.Awesome());
        }
    }
    class Enrick
    {
        public string Awesome()
        {
            return "Awesome";
        }
    }
}

 

Yep, that method isn’t static. It’s an instance method, but you would have been able to call it.

So to see that in action why don’t we disassemble this code and make the change directly to the intermediate language.

First we need to get the IL using ildasm, so open up the VisualStudio 2008 Command Prompt and type this command.

ildasm PathToTheExecutable /out:new.il

This will create a file “new.il” in our VS Command Prompt working directory.

Now we can open this in our favorite editor and we will see a bunch of code. We are just looking at this main method though.

.method private hidebysig static void  Main(string[] args) cil managed
  {
    .entrypoint
    // Code size       16 (0x10)
    .maxstack  1
    .locals init ([0] class NullInstanceMethod.Enrick brendan)
    IL_0000:  nop
    IL_0001:  ldnull
    IL_0002:  stloc.0
    IL_0003:  ldloc.0
    IL_0004:  callvirt   instance string NullInstanceMethod.Enrick::Awesome()
    IL_0009:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_000e:  nop
    IL_000f:  ret
  } // end of method Program::Main

See IL_0004 there is our callvirt that makes the call to our instance method. If we change that to a regular call we should be good.

Now we just put the IL back into the assembly.

ilasm new.il

And we execute it and here is the result.

CallSuccess

 

 

And there you have it. I just called an instance method on a null instance of a concrete class without getting a null reference exception? Strange? Yes. Wrong? I don’t know if it really is.

For your homework I would like you to consider what would happen if I were calling an interface’s method instead of a concrete class.

Why I Prefer Web Application Projects

Over the summer, Nimble Pros brought on some new interns. We of course brought them up to speed on how we do things here. We like the integration process of bringing new employees into the mix immediately involving them in the process the entire team is involved with. To help get them up to speed we use a combination of pair-programming, book and article reading, and formal instruction.

As I am sure anyone who uses Visual Studio for web development knows, there are two main ways to go about creating the site that you’re going to develop. There is the web application project (WAP) and the web site (ignoring MVC of course).

Back in the days of ASP.NET 1 there was only one way of doing things, web application projects. ASP.NET 2 got rid of WAPs and replaced them with web sites. Not entirely sure why, but it did not take long before Microsoft added Web Application Projects back into the mix. These were able to be installed and added into Visual Studio so they could be used again.

I of course switched to these as soon as they were readily available. The title of this post kind of gives that away. I switched for a few reasons including the dueling assemblies issue which can occur with web sites. I have written about dueling assemblies and some of the differences between these methods of developing sites before.

The main reason why I prefer having a project is that I like being in control. Now you might wonder how I can have more control with a project file. It might seem that the less controlling approach would give me more control, but it is not the case. The loose collection of files, lovingly referred to as a web site is hard to control. I can’t say what is included I can’t say what is excluded. My only control is the relative locations of files. Inclusion of a library? Oh that is a refresh file in the bin folder.

Sure I can get some control in a web site’s loose structure, but I feel that I get so much more control from the project file. I have something obvious to point MSBuild to. I have settings and targets I can manipulate in the file. I have direct control of which files are in the project. Heck I can control which version of a dll I am using which means no more dueling assemblies. Hooray!

Perhaps you disagree. I prefer the WAP to the web site. Do you have any good reason to think otherwise?

Recommended Reading List

Just like many other developers I know, I have a stack of books I intend to read high enough that I could not hope to finish them ever. I know that the stack will increase in size as fast as I finish the books. I have plenty of technical books I intend to read as well as a large quantity of those which are purely for my own entertainment.

Required Developer Reading

I think it is very important to continue reading and learning to be a better developer. Here at Nimble Pros we make sure that our developers know what they should be reading, so every time we hire someone I make sure that they get there hands on these books. While not required, we highly encourage our developers to take the time to read these excellent books.

Code Complete – This is a classic that is on a lot of reading lists. I read this one a few years ago, and I really think that you should read it if you have not. It is a fairly large book that covers a variety of topics with a great deal of depth and breadth. It really is worth the time and effort to read.

Working Effectively with Legacy Code – While the name of this book is somewhat misleading based on people’s definition of “legacy code”, I still believe this is one of the most important books for every developer to read. Michael C. Feathers wrote an excellent book with this one. Every developer is going to need to work with legacy code constantly during their time as a developer. We don’t always work on green-field projects, and this book takes a hands-on approach to explaining how to deal with and fix up legacy code.

I am Currently Reading

Yesterday, I started reading Clean Code, which is a book I am already fascinated with. I mention this because I believe it will make the above list once I am done reading it. I have only just started reading it, but I’ve already got plenty of notes I’ve taken as I’ve been reading it. I plan on discussing as much as I can about the book and its topic as I  read it.

Look forward to some blog posts responding to this great book.

The Joy of Removing Code

Removing code is one of my favorite activities. Isn’t it one of yours? As a software developer I strive to write less code. Sounds kind of funny, but what I mean is that I want the code that I write to be reused as effectively as possible. Having less code means that maintenance is easier. I can fix things faster, change things faster, find things faster, and figure things out faster.

This is a very good case of “less is more”, which is one reason why I love removing code. I really enjoy getting more or even equivalent work done with less code.

I just finished eliminating a constructor. Why? Well, it really was not needed. As it turns out there was a more appropriate constructor to use for the class. Not sure when or why the constructor was created, but it doesn’t really matter. I am fairly certain that nothing is using it after my removing it. Code still compiles. Tests still pass.

This does a lot of good things. It makes the class less intimidating by dropping the line count. It makes clearer which constructor to use when there are fewer of them. If I need to make a change to the constructor by either adding or removing a parameter for example there is only one place to do this now. Before there were two places.

I love writing code, but I also enjoy removing excess code. It just makes things simpler, which is exactly how I like things. I want my code to be just complex enough to work. When I am refactoring old code this is one of the best things to do. Chopping off all the bits and pieces of unneeded legacy code is progress.

Has anyone else removed any code recently they were glad to be rid of? Anyone eliminate any entire class libraries or anything cool like that?

“Do you want complexity with that?”

“No, thank you.”

Fast Beats Right, a Principle of Mediocre Programming

Steve Smith just posted an interesting set of anti-principles, anti-patterns, and anti-practices that make up mediocre programming. In the post one of the principles of mediocre programming that Steve mentions is,

Fast Beats Right (FBR) – It’s more important to get something done that probably works, or that works right now even if it will be hard to change later, than to spend time ensuring that it is correct or is well designed.

I think we’ve all seen people who code this way before. They’ll get the really quick, dirty solution in place. Steve also makes note of what he has experienced as management’s opinion of this behavior.

sometimes management may be OK with dictating that for a given feature or prototype, speed is more important than anything else

The really scary part here is that there are managers who think that faster == better. Some teams have programmers following this principle and the managers think those are the best programmers. Why? Well, that guy gets lots of new stuff done. These other guys don’t (because they have to clean up the crap the fast guy writes.) Sure, for any task that is small enough I can do the work really quickly without testing or structuring things correctly. However, it might not work for all cases. The code could be fragile. It is very hard to determine how well it will stand up. Down the road I might need to add on to that code, and it could be so bad that it needs to be completely rewritten.

I really hope that no one is stuck at an office where management believes that an FBR programmer is a good programmer.

Have you every worked with a coder like this? What was the opinion of developer from the management point of view?

How Coding Katas Can Help You

Here at Nimble Software Professionals one of the activities that we have started doing is coding katas. We do these to help hone our skills as software developers. We do them because we value continual improvement among our team. The importance of an ever-growing, ever-improving team is very important, and through constant training and reemphasis of these techniques we expect to be able to achieve this important endeavor.

As developers we are presented with problems we must work through on a regular basis. Solving these problems is easier if we know all of the theory and mechanics to help us along the way. Knowing design patterns helps, since these are patterns which occur often enough that there is a repeatable solution. You can also just be a programming genius, and that will also help.

So how useful is it to know a bunch of design patterns? Not very if you haven’t had experience using them. You will not see the opportunity to use it if you haven’t seen it used or used it. Through training and practice you will learn what works when and why.

A kata is about solving a known problem. The standard way to do a kata is to follow along with someone who knows how to solve the problem. Following along with someone will let you see how to solve the problem the correct way. This is designed to help you think and solve problems the same way as that known smart person solves problems.

That is a great approach, but I prefer doing that after trying to solve the problem my own way. This lets me get my own perspective on solving the problem first. I can then compare my thought process with the one of the kata leader. Perhaps I prefer something I did over something they did.

The kata should be repeated again later. This time you’ve done it before, so your new solution should be better. Once you finish once again compare with how the leader did it. Make improvements like this every time until you have either the same thing as the leader or until you’re satisfied with your solution. Once you reach that state you will still do the same kata, but attempt to repeat the same solution, so that the process for solving the problem is well understood. You want to know how to solve problems. You do not want to think about how to solve problems.

One of my favorite katas is the Bowling Game Kata. One of the reasons I like it is because my first time solving the problem I created a solution nothing like the one that the kata teaches. From the kata I have improved how I do things. In my first solution for it I violated YAGNI.

My solution worked very well, and if there would have been more development of the problem my solution might have ended up being “better”. But it is true that I do not know what might come for the project in the future my solution was not as good, and since then I have been training myself to not make the same mistake again. By following along with the kata I’ve learned to improve the development process I use.

How to Add a ToolTip to a RadGridView

So I was using a RadGridView to display some data and I wanted to add a tooltip with more information. Shouldn’t be too difficult. I of course checked through intellisense to see if there were any obviously named properties for setting a tooltip.

I checked on the RadGridView tag for the properties and I also checked the GridViewDataColumn for it. Didn’t come up with anything so I Binged until I found a potential solution. It didn’t really make sense to me and the solution had me doing a lot of what seemed like extra stuff. It was adjusting the tooltip using the styles for the cell. So, then it hit me that I was thinking about this the wrong way. Since I just wanted text and a tooltip why don’t I just add that in?

So I took control of things and I just used a template for the column instead. Here is the quick and easy way to add a tooltip into a RadGridView.

<grid:RadGridView x:Name="RadGridView1" AutoGenerateColumns="False">            
    <grid:RadGridView.Columns>
        <grid:GridViewColumn Header="Person">
            <grid:GridViewColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding NickName}" 
                       ToolTipService.ToolTip="{Binding FullName}" 
                       VerticalAlignment="Center" />
                </DataTemplate>
            </grid:GridViewColumn.CellTemplate>
        </grid:GridViewColumn>
        <grid:GridViewDataColumn Header="Place" 
          DataMemberBinding="{Binding Place}" />
        <grid:GridViewDataColumn Header="Thing" 
          DataMemberBinding="{Binding Thing}" />
    </grid:RadGridView.Columns>
</grid:RadGridView>

 

And there you have a tooltip on the text of a cell in a RadGridView. You can obviously add different content items into the DataTemplate so that you can support more advanced templates. Just throw the tooltip on the root element inside the DataTemplate and you’ll be set.

Programming is Not Just Typing

One of my favorite quotes about programming languages comes from Ward Cunningham who said, “If you don't think carefully, you might think that programming is just typing statements in a programming language.” Not sure if he really said it, but it is attributed to him plenty of times on the Internet.

So back to Ward Cunningham for a minute. I really like that quote. It says one very powerful thing about programming that I think is known by a lot of people using programming languages, but I am not always sure they think about it in this manner. I know that non-programmers certainly don’t understand it. Plenty of people think that all we do all day is type, but there’s a heck of a lot more to it than that.

Nearly a year ago, when Jeff Atwood posted about our being Typists First and Programmers Second, I was quite appalled. Here is one of the most respected individuals in our industry, and he’s making a statement like this in a blog post. Sure I agree that one of the core skills that every programmer needs is the ability to type. I don’t disagree with the importance of typing. I think a programmers ability to quite quickly and accurately is extremely important. He says in the post that there are other things of importance, but I refuse to say that our primary skill is typing.

Although I find that programmers should spend some time thinking and some time typing. If you’re typing non-stop as fast as you can then you’re probably not thinking enough about what you’re typing.

Like broken clocks, even pointy-haired managers are right once a day. Coding is just typing.

This is a bit crazy to me since I work on code every day. I can certainly say that coding is not just typing. This is one of the reasons why I am an advocate of pair programming. I think that a fair amount of time needs to be spent thinking. All programmers need to be able to type quickly, but the core of what we do is the thought and design that goes into making an application that we can be proud.

Don’t get me wrong I have the highest respect for Jeff Atwood. I think he is one of the greats. I just disagree with the priorities here. I believe that a developer can certainly benefit from typing faster. In fact I wish I did type faster. I certainly don’t hunt and peck. I’ve typed without looking at the keys since I was a kid. I can touch-type the “correct” way, but I have my own style that has worked for me since i was a kid.

Most of the development I do these days is pair programming. An Extreme Programming technique I am sure most of you have at least heard of. This technique is an excellent one that I believe produces better software. Why? Well for one because it lets developers spend more time thinking and less time typing. Both guys are thinking, but about different things. One developer has the keyboard at any given time and keeps in his head the path he is on. (This guy is concerned with typing speed.) He types along the path thinking about the code he is currently writing not the structure of the app, but the code he is typing right now. For a short time his typing speed matters.

The programmer in the pair who is not actively typing is spending all of his time thinking. He keeps in his head the path that the typist is taking, not concerned with the syntax of the programming language. That is the other guy thinking about the language syntax. The one sitting back without the keyboard is the guide. He must make sure that the pair stays on the right path using the most efficient route to success.

By spending time thinking the pair is able to take the smarter path to their goal. Rather than brute-force typing speed we use intelligence of our development team to ensure successful work. This isn’t to say that we shouldn’t type very very fast, because typing fast sure does help us be better developers. However, more important than our typing speed is our thinking speed.

If you’re considering your typing speed to be more important than your thinking speed then I am concerned to see how you’ve structured your code in such a way that you need to type very fast. I find that well structured code requires a lot less typing and a lot more thinking.

If you pause and consider for a minute who are the most revered of developers in the world. Do they type fast? I bet most of them do. Is that why we revere them? No probably not. The greatest of people who code are some of the greatest minds in our industry. They are not the greatest typists in our industry. If you could type 200 WPM do you really think your code would be that much better? I doubt a developer could get more than a 10 or 15 percent increase in efficiency even typing that fast. But if you could think twice as fast I am sure you would see a much larger increase in how efficiently you wrote code.

Good luck with either endeavor, but don’t tell me I’m a typist. I am a thinker first and a typist second, and I refuse to let anyone tell me otherwise. Just because someone can type and knows a programming language does not mean that they can create software of any value.