On Importance of Good Method Names and Paying Attention

I spent a somewhat frustrating hour at work today trying to plot a straight line on a chart using a framework that shall remain nameless. I quickly had the slope and the y-intercept worked out and all I needed were two x values to plug into the equation to calculate some points. I already had another series plotted on the same chart and just picking the minimum and maximum x values from it was sufficient for my causes.

Naturally, I could do the legwork of figuring the min and max myself, but why do the work when the framework can do it for you? I poked around and found a couple useful methods: FindMinValue() and FindMaxValue(). I had assumed (based on Intellisense and lack of code docs) that they would return the values I needed. Then a couple things taught me that wasn’t so at all:
1. I used var to declare my variables, so I didn’t notice that the functions in question are returning integers.
2. I was wrong in my original assumption. Those methods aren’t finding and returning the min and max values. Instead, they’re returning indices into the array of points in the series, pointing me to the location of the min and max values.

I guess technically the method names didn’t lie: they are “finding” the location of the values for me. I still found that to be counterintuitive. In my opinion, FindMinValueIndex() would’ve been better.

So, the lesson is: pay attention, don’t assume anything, and if you ever release an API framework, try to be as clear as possible about the intent of your methods when you name them.

ComboBox SelectedItem vs SelectedValue Question

Annoying discovery of the day:

The following code works as you’d expect — MyProperty on the model is updated when the user picks a new item in the dropdown.

comboBox1.DataBindings.Add("SelectedValue", myModel, "MyProperty", true, DataSourceUpdateMode.OnPropertyChanged);

The following, however, doesn’t work the same way and the model update isn’t triggered until the input focus moves to another control on the form:

comboBox1.DataBindings.Add("SelectedItem", myModel, "MyProperty", true, DataSourceUpdateMode.OnPropertyChanged);

Does anybody know why? I’d investigate myself, but I don’t even know where to start. Pointers in the right direction to start the investigation or an outright explanation are both welcome.

Update: Some explanations are up on StackOverflow. In the end, I ended up binding to both SelectedValue and SelectedItem, which ensures instant model updates based on UI changes (through the SelectedValue binding), and UI updates based on programmatic model changes (through the SelectedItem binding).

Another thing to note is that when binding to SelectedValue without setting the DisplayMember/ValueMember properties, it helps to pass in “true” for the formattingEnabled binding parameter.

Replace Paper with Unit Tests: Code Snippets Edition

In my previous post about making mental notes about condition tests or new features through unit tests I offered an example of making a live template in ReSharper to automate some of the process.

This post is about achieving a similar thing in plain Visual Studio with the help of the Code Snippets feature.

Introduction to Code Snippets

In a nutshell, a code snippet in Visual Studio is either a template or a static chunk of code that is stored in a specific location and is available through IntelliSense. Visual Studio comes with some snippets pre-configured, such as “ctor“, which creates a default constructor for a class.

To use a snippet, start typing out its shortcut – either type the whole thing or wait for IntelliSense to pop up and complete it for you – and then press TAB key twice to expand the snippet into code.

There’s a detailed guide to using and creating snippets available on MSDN. For the rest of this post, I will just show what I did for my purposes.

Snippet Location and Creating New Snippets

Snippets are located in a specific folder under your installation of Visual Studio, so you’ll have a snippet collection per VS version. On my machine, where I used default installation paths, C# snippets for VS 2008 and 2010 are in the following folders:

C:\Program Files\Microsoft Visual Studio 9.0\VC#\Snippets\1033\Visual C#

C:\Program Files\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Visual C#

You can use the Code Snippet Manager (available through Tools->Code Snippets Manager… menu item) to explore currently installed snippets for various languages.

To create a new snippet, you can simply write its XML definition (see below for my example or read the MSDN guide for more info), save the file with the .snippet extension and drop it in the appropriate folder. Visual Studio will see it without needing to restart.

You can also use a visual editor such as the open source Snippet Editor, which now includes support for Visual Studio 2010.

Unimplemented Unit Test Snippet

Here’s my code snippet in its entirety:

<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Unimplemented Unit Test</Title>
<Shortcut>test</Shortcut>
<Description>Code snippet for a failing test placeholder</Description>
<Author>Anna Lear (http://annalear.ca)</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>testName</ID>
<ToolTip>Descriptive test name</ToolTip>
<Default>NewTest</Default>
</Literal>
<Literal>
<ID>testBody</ID>
<ToolTip>Test contents</ToolTip>
<Default>Assert.Fail("Implement me!");</Default>
</Literal>
</Declarations>
<Code Language="CSharp">
<![CDATA[
[Test]
public void $testName$()
{
$testBody$
}
]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>

I wrote it within Visual Studio 2010 and it helpfully provided IntelliSense support and guidance, which made writing the XML really easy.

Now when I type in “test” in a class and press TAB twice, the code within the CDATA portion of the snippet gets pasted into my code. “NewTest” and “Assert.Fail(“Implement me!”);” lines will be highlighted and I can navigate between then with TAB and Shift-TAB if I need to edit them. I typically always edit the name of the test, and only edit the body when I intend to implement the test at the same time.

Couple things to keep in mind:

1. When you add literals to a snippet, their IDs are case-sensitive.

2. If you want to preserve your formatting (multiple lines, etc.), make sure that you’re code is within a single CDATA element. Otherwise you’ll end up with all your code on the same line, which probably isn’t what you want.

Download

You can either copy the snippet above and do the legwork of placing it in a file and the correct location, or download the .snippet file or the .vsi installer, the latter of which will allow you to easily install the above snippet into any version of Visual Studio (2005 or newer) that you have on your machine.

Toronto Code Camp 2010: Lessons Learned

This weekend I had the great opportunity to attend Toronto Code Camp 2010. It was my first code camp and my first major dev-related event, so I was pretty excited all around. I’m happy to say it didn’t disappoint. Over the next few days I’ll post some of the notes I’ve made and/or links to slides if I can find them, but for this point I’d like to just list some of the lessons I learned.

In no particular order…

1. Having business cards on hand is important.

Every conversation I had in-between sessions ended with an exchange of business cards. The ones I had with me were employer-branded, which is better than nothing, but I think I will be making some of my own soon.

2. Talks that look irrelevant may turn out to be very enjoyable.

I’m primarily a desktop application developer just starting to poke my nose outside .NET 2.0. I was worried for a bit that the event was very focused on technologies I don’t work with. Well, lesson learned: that doesn’t matter. Learning something outside my normal work was perhaps one of the most valuable things I took home with me.

I would almost go as far as to say “go to talks on subjects you know nothing about”.

3. Bring food.

The code camp’s organizers, volunteers, and sponsors do an excellent job of bringing a free event out to the developer community and provide a free (!) lunch to the majority of the attendees. Alas, for a day full of thinking, it would be helpful to have some “brain food” on hand throughout the day.

I didn’t bring anything along this time and my afternoon sustenance was comprised of a Coke and a Bounty bar out of the vending machine. This is not a mistake I plan on repeating.

4. Even though they may work with different programming languages or technologies, all developers speak code.

I don’t think there’s anything else I need (or have to) say about this one. When in doubt, sketch out some code on a napkin. Maybe clarify the syntax. And suddenly you’ve explained a concept to someone even though you’re working in drastically different areas.

5. Don’t be shy.

I only recently began coming out to user groups and other dev-related events and I gotta say that writing code in isolation, no matter what you’re working on, isn’t nearly as fun as coming out and meeting other people with the same interests. So don’t be shy. Say hello to the person next to you, ask about them and tell them about yourself.

Conclusion

I came home from the camp both incredibly inspired and incredibly worn out. “Information overload” didn’t quite cover it. Now that I’ve had time to process, I can safely say that the event, for me, has been a blast. I regret being unable to stay for the afterparty and meet more people, but that’s something to fix for next year as well.

For now, I’m excited about the Microsoft Web Camp coming up on May 7 and 8. And after that… who knows?