Archive for November, 2007

Good Resources on Test-Driven Development (TDD)

Since I’ve been doing some introductory presentations on Test-Driven Development (TDD), and introducing more and more people to it, I keep being asked about resources for them to go do some more research. So I’ll post here a list of resources I think to be valuable.

Articles

Robert, a fellow co-worker, pointed our developers out to this article, which is a good and quick introduction to TDD.

This is another good article by Roy Osherove.

Here’s a great article on Mock objects.

Books

A good introductory book to the topic is this one:

Test-Driven Development in Microsoft .NET (Microsoft Professional)
by James W. Newkirk, Alexei A. Vorontsov

Read more about this title…

A book that’s not directly based on TDD, but that uses TDD all across is the one below. This is probably my favorite book out of the last couple of years. I’m still reading through it, but I loving each and every page of it. I’ll probably end up writing a lengthy post (or a few smaller posts) about this book soon.

Agile Principles, Patterns, and Practices in C# (Robert C. Martin Series)
by Robert C. Martin, Micah Martin

Read more about this title…

Blogs

There are blogs that I follow that always have some great information on TDD:

Roy Osherove

Jean-Paul Boodhoo

Eli Lopian (TypeMock)

Ayende Rahien

Web Casts

Jean Paul Boodhoo on Test Driven Development: Part 1 and Part 2

Tools

Two tools I really can’t live without when doing TDD:

Test-Driven.NET (I blogged about it a while ago).

TypeMock

More Resources

I know there are plenty more resources out there. The ones I’ve listed here are just the ones I’ve either used or have been using myself. If you know of any others that you really like, please let me know.

Advertisements

Leave a comment

The Surgeon hobbyists and the Developer hobbyists

While a lot of developers are sunk deep into trying out new technologies such as WPF, WCF, LINQ, etc. (I’ve done a little bit of that too), I’m currently reading up books and articles that deal with architecture (design patterns, best practices, etc.). And I’m having a blast! As usual, I’m going back to further explore into some areas that I’ve researched and used before, but of course I’m doing that with a new perspective, given the knowledge I’ve acquired since the last time I’ve done so.

I was than thinking about something: usually, they way Microsoft and other writers and speakers throw new technologies at us isn’t even close to the way that should happen.

I mean, I remember several years ago when I was at a presentation where the speaker was showing one of the new features in VS 2005. He had VS open, created a brand new form, went to the Data Sources window, selected some table in SQL Server, dragged the table onto the form, and voila, controls get automagically created on the form (textboxes, checkboxes, VCR buttons), everything already bound to the data.

While the speaker still had this air of satisfaction on his face due to the cool new feature he had just demoed, I heard attendees gasping, incredulously. For how many had we already seen that that was just NOT the way of creating applications? UI controls bound directly to columns in a table on the SQL Server database? What if tomorrow the customer wants to migrate to Oracle? What if the customer wants to migrate to a web application? What about the business logic?

People who doesn’t know any better would just go back home and start creating applications in that way. Worse yet, they’d show it to other people, and the plague would spread like there’s no tomorrow.

Later on, the option to select "object" as a data source was introduced (allowing developers to bind controls to special objects, such as Entities, Data Transfer Objects, etc.), as opposed to binding directly to a database. But why not prioritize that option, promoting the concepts of an application well designed, instead of going with the cheap, quick and dirty, unprofessional option?

An analogy for that is to have a presentation for surgeons, where the presenter goes like "hey, this is a flashy looking new scalpel, which cuts skin open so quick and easy that you don’t even have to think about when you’re performing a surgery. Ain’t that cool?".

Wait, maybe there’s still hope…

With all that said, I was just thinking how great it was to see Scott Guthrie presenting the MVC Framework first-hand at the Alt.NET in Austin last month. In case you missed it, Scott Hanselman has a good post about it, including videos of the presentation.

To me, that was huge. There was no drag and drop. There was no quick and dirty way of implementing something. Mr. Guthrie did the presentation totally based on strong concepts, such as separation of concerns, inversion of control, test-driven development, the MVC pattern itself…

I’m honestly hoping that we get to see more of this type of presentation and tool coming out of Microsoft, from the mouth of influential people such as Scott, since their reach is broad within the software development world (well, at least the part of the world that works with Microsoft technologies).

Any Surgeon hobbyists out there?

We don’t hear about surgeon hobbyists, or fireman hobbyists out there, do we? Nobody starts practicing those profession just by reading a "…for Dummies" kind of book (I guess we can’t even use "profession" and "hobbyist" in the same sentence…). So why do we have so many developer hobbyists then?

Sure, one cannot just "play" being a surgeon, whereas it’s easy and harmless to play being a developer. If a hobbyist decides to turn that into a profession, then he or she should become a professional. That means go learn the practices. Go learn the more appropriate tools. Go learn pros and cons of doing something one way as opposed to another.

The sad thing is that even for the more seasoned developers (people who’s being doing this for so many years now), there’s still a lack of notion that some tools (such as Visual Studio) don’t necessarily promote good practices. Those tools usually offer features for RAD (Rapid Application Development), which demos well for the masses, but don’t really help developers who are trying to follow better practices and processes (such as TDD, loose coupling, n-tier development, etc). There are other examples of this that come to my mind, but I’ll keep those to another post (just trying to keep this one not too long…).

So, are you a hobbyist or professional developer?

3 Comments

More on the keyboard, less on the mouse…

I’m becoming more and more of a keyboard freak. It’s so much quicker to do stuff using the keyboard as opposed to using the mouse. If you’ve been following my blog you probably know I’ve been posting a bunch of things related to productivity.

By observing other people work I notice (in horror) how much time they spend moving their hands to reach the mouse, move the mouse pointer on the screen, hit the correct pixel to open a menu or smart tag, select an option (sometimes we select the wrong option, and then the slow ritual has to begin again…), and then go back to the keyboard. Most of the time there are quick shortcuts to accomplish the same task in a fraction of a second. If there isn’t a shortcut, there probably are ways to create one. If you’re not too familiar with standard shortcuts already available, check out this post.

It’s not that I think the mouse is totally useless. That’d be stupid. I just think there are a bunch of things that the keyboard is better suited for; and there are definitely things the mouse is the better choice.

When I’m working on my laptop, I really like using the Trackpoint as an input device. The thing that attracts me is that I don’t have to take my hands off the keyboard so to get the "mouse" behavior. It’s all there, just beneath my fingertip. I’m actually considering getting an external keyboard with a Trackpoint to use on my desktop machine. On the other hand, I can’t stand the Touchpad. That thing I just can’t use to save my life. I actually ran across this good post about it Touchpad versus Trackpoint. The author’s preferences are actually the opposite on mine, but it’s interesting to read some of the comments people left there, favoring either one or the other device. The bottom line is: if you need to use the mouse, it’s much better if it’s sitting right beneath your fingertip.

SlickRun and Windows Vista "Start Search"

vistaLike I’ve mentioned a few months ago, I’ve chosen SlickRun as my launcher program. Even though the "Start Search" feature in Windows Vista is kind of handy, I believe it’s only handy when you’re "searching" for something (like when you’ve installed a program and don’t know where it went; the Vista search usually makes it easier for you to find it). But if you already know what you’re looking for, why waiting for the search??

You still also need to wait for the search to happen. And you also need to wait for the window to come up. Sometimes that’s a flash of a second, but sometimes it takes several seconds, just because Windows is busy rendering or doing something else.

Since SlickRun shows a pretty simplistic user interface (who the heck needs fancy interface for something like this anyway?), it shows up extremely quick, and you don’t have to wait and search to happen.

For instance, say I want to launch Visual Studio. If I use the Vista Search, I hit the Windows-key, and type "V". After a few seconds, Vista shows me a list containing not only Visual Studio, but also Visio, Event Viewer, plus a bunch of other stuff.

Well, with SlickRun, I’ve just set a "vs" magic word, so it takes almost no time for me to hit Windows-key+Q, type "vs", and hit Enter. Also, if "vs" was the last magic word I’ve used, I can type just "v", instead of "vs", and I’m right there. Of course, saving one keystroke doesn’t sound impressive, but if you’re navigating to paths, or anything longer, than you start to appreciate this feature even more.

Quickly creating a new email

That all said, one thing that was bothering me is to create a new email. You know, as I’m working, sometimes I remember I have to send an email to somebody. There I go, get the mouse, click on Outlook, find the "New Email" button somewhere, yadda-yadda-yadda. I finally broke down and created a "mail" magic word in SlickRun. This is the magic word definition for it:

mail

That shortcut brings up the "new email" screen immediately.

Yeah, one could hit the Windows-key, type "mailto:" and hit Enter, but I prefer to just hit Windows-key+Q, type "m", and hit enter. Yup, I’m that lazy (plus, again, why trigger a Windows Search, when I already know precisely what I’m looking for?).¬† ūüėČ

Leave a comment

My daddy is on youtube!!

Some weeks ago I posted about how I try to keep myself busy and alive when I’m on the road for training, consulting, and speaking gigs. One of the things I had mentioned was about my new little "traveller" guitar and Tascam "guitar trainer" (see the post for links and pics). Those two things are awesome!

Last month I’ve spent a week in Eugene, OR, and on the evenings I was playing guitar for about 2 hours, practicing a song by Joe Satriani, Always with me, Always with you. In one of my training gigs, fellow former VFP MVP, Rick Bean, gave me a DVD with guitar lessons of how to play some of Satriani’s tunes, so I used it to relearn this song (I used to play some parts of it many years ago…).

So now I’m bringing the two toys to the office everyday, so that I can play guitar for about 30 minutes. This has been great! It helps a lot keeping up with my chops, and giving my brains a break for a change.

A few weeks ago my friend Milton captured a few minutes of one of my lunch breaks while I was playing the Satriani tune. Check it out! The funny part of it was when my 7-year old daughter saw the video on youtube and went bananas through the house, yelling to some of her friends: "my daddy is on youtube, my daddy is on youtube! He’s going to be famous and millionaire!".¬†So cute.¬†¬†=:-D¬†

2 Comments

Working with Enums

Since I’m always getting questions about handling enums, I decided to blog about it.

Back to the basics

First let me cover some ground for those who are not familiar at all with enums. If you are familiar with them already, just skip this section.

Say we have some code somewhere that looks like the following:

Console.WriteLine(SayHello((0)));  // prints out "Hello, Administrator!"
Console.WriteLine(SayHello((1)));  // prints out "Hello, Developer!"
Console.WriteLine(SayHello((2)));  // prints out "Hello, Secretary!" 

There’s no question about those parameters being passed to the SayHello: they’re¬†magic numbers that should be avoided like the plague.¬† ūüôā

 The SayHello method looks like so:

private static string SayHello(int role)
{
    string roleName = string.Empty;

    switch (role)
    {
        case 0:
            roleName = "Administrator";
            break;
        case 1:
            roleName = "Developer";
            break;
        case 2:
            roleName = "Secretary";
            break;
    }

    return String.Format("Hello, {0}!", roleName);
}

Enter the Enums

Instead of passing magic numbers to the SayHello method, we could use an enum instead. The enum could be defined like so:

public enum Roles
{
    Administrator,
    Developer,
    Secretary,
}

The SayHello should then be changed to:

private static string SayHello(Roles role)
{
    string roleName = string.Empty;

    switch (role)
    {
        case Roles.Administrator:
            roleName = "Administrator";
            break;
        case Roles.Developer:
            roleName = "Developer";
            break;
        case Roles.Secretary:
            roleName = "Secretary";
            break;
    }

    return String.Format("Hello, {0}!", roleName);
}

And then could be called like so:

Console.WriteLine(SayHello((Roles.Administrator))); 
Console.WriteLine(SayHello((Roles.Developer))); 
Console.WriteLine(SayHello((Roles.Secretary))); 

It sure sounds more readable, right? No more need to either decipher magical numbers or pollute the code with in-line comments describing what the magical numbers mean.

The Enum’s underlying value

By default, the underlying value of an enum is an integer. Each member of the enum gets a value assigned to it automatically, starting with zero. One could change the way the values get assigned by just assigning them directly. For instance, our Roles enum could be changed so that the first item gets assigned the value of 4, and then all members get assigned incrementally from there:

public enum Roles
{
    Administrator = 4,
    Developer,
    Secretary,
}

Alternatively, each element could have a different value assigned to it:

public enum Roles
{
    Administrator = 3,
    Developer = 1,
    Secretary = 2,
}

That could be helpful because the enum could be mapping to values that get stored to and retrieved from a database, so that underlying value may be very important. The cool think is that nothing has to be changed on the places where the enum is used.

Little gotcha: don’t ever trust values being received as enums!

Because our Roles enum uses ints for its underlying value, the following code is valid:

Console.WriteLine(SayHello((Roles)1));

Since the number 1 can be cast to the Roles enum, the compiler is okay with that code. During runtime, things also work fine, because 1 maps to the Developer option within the enum. This is great, because the integer value could be coming from a database, so we could map database integers from a column to values of an enum.

However, what about the following code:

Console.WriteLine(SayHello((Roles)99));

Hmm, currently, there’s no element in the enum that maps to 99, which means that the switch statement in our SayHello method wouldn’t know how to handle such value. So this is something to keep in mind: never trust what you’re getting as an enum!

One option to address this issue is by always providing some default whenever an unknown value is passed as an enum. For example:

switch (role)
{
    case Roles.Administrator:
        roleName = "Administrator";
        break;
    case Roles.Developer:
        roleName = "Developer";
        break;
    case Roles.Secretary:
        roleName = "Secretary";
        break;
    default :
        roleName = "Unknown";
        break;
}

That works as¬†long as the requirements¬†for the method say it’s fine to have a default value. However, there are cases where unknown values should not be allowed. The way to accomplish is by checking whether the given value is actually defined in the enum, like so:

private static string SayHello(Roles role)
{
    if (!Enum.IsDefined(typeof(Roles), role))
    {
        throw new ArgumentException("Given role is not valid.", "role");
    }
    ...
} 

So remember: either handle bad values by having a default value, or just reject the input by checking whether the given value is defined in the enum or not. 

Use the ToString method on an enum

It’s pretty easy to use¬†the string representation of an enums value; all we have to do is to call the ToString method on it! For instance, our SayHello method can be rewritten in the following way:

private static string SayHello(Roles role)
{
    if (!Enum.IsDefined(typeof(Roles), role))
    {
        throw new ArgumentException("Given role is not valid.", "role");
    }

    string roleName = role.ToString();

    return String.Format("Hello, {0}!", roleName);
}

Getting all strings out of an enum

Another common thing to do is list out all the elements of an enum as its string representation:

foreach (string element in Enum.GetNames(typeof(Roles)))
{
    Console.WriteLine(element);
}

The GetNames method on the Enum class returns a string array containing the string representation of each item defined on the given enum type.

Using enums to populate lists

It’s also very useful to use enums to populate lists (such as DropDown controls). The code below lists out all the elements of an enum, printing out both the underlying value as well as the string representation (those values can be used as the ValueMember and DisplayMember on a DropDown, respectively):

Type enumType = typeof(Roles);
foreach (int elementValue in Enum.GetValues(enumType))
{
    Console.WriteLine(String.Format("Value Member = {0} / Display Member = {1}",
        elementValue, Enum.GetName(enumType, elementValue)));
}

GetValues returns an array of integers (that is, if the underlying value of the enum is integer; the default), whereas the GetName method takes in the integer value and returns the string representation of the element. The code prints out the following:

enum[1]

Notice that both GetValues and GetName takes in a Type object, therefore, it uses Reflection to figure out what elements and values are declared on the specific enum type. It is a good idea to create a variable to store the Type object and reuse the same variable for both methods, as opposed to creating the Type objects every time.

Parsing a string into an enum

There are cases where what we have is the string that maps to an element on a enum, and we need to create an actual instance of the enum based on that string. The string can be parsed into an enum like so:

string foo = "Developer";
Roles role = (Roles)Enum.Parse(typeof(Roles), foo);

Note that the Parse method returns an object, so we always need to cast that object to the specific enum type that we expect.

Also keep in mind that the Parse method will throw an ArgumentException in case the string cannot be parsed into an enum element, so make sure to always check it and act accordingly:

string foo = "Teacher";
if (Enum.IsDefined(typeof(Roles), foo))
{
    Roles role = (Roles)Enum.Parse(typeof(Roles), foo);
}

Final Thoughts

Enums are certainly not the answer to everything, but they’re certainly helpful, and whenever they are the best choice for whatever it is you’re implementing, it’s good to know how to make the best use of them.

Also, make sure to check out this other post, "Fun with Extension Methods and Enums".

Leave a comment

Design Apps for Future Flexibility

Last week I ran across this article:

Design Apps for Future Flexibility

It is a great quick read on proper abstraction and encapsulation.

Leave a comment

DataBinding, DevExpress controls, synchronization of Ribbon control, etc.

Oh boy, this was an interesting one…

Here at the company we have our application framework, and we also have a little framework that sits on top of the DevExpress DXperience controls suite. We have an edit form that has the typical CRUD buttons on the Ribbon. Those buttons get enabled/disabled depending on the context (if the data is "dirty", both the Save and Undo buttons become enabled; otherwise, they’re disabled):

dr

Now, say the user launches an edit form, puts the cursor in a TextBox, types something in, and clicks the Save button. Clicking directly on the button on the Ribbon does not cause the TextBox to lose its focus, and because of the way databinding works in .NET, the changes made to the TextBox never get pushed into the underlying object the control is bound to (most likely, a property in a Business Entity).

Just for the records, databinding doesn’t update the underlying value immediately for performance reasons (changing the underlying property may cause a series of changes, and we don’t want that to happen every time¬† the user hits a keystroke within a TextBox).

We created a method, ForceDataBindingToSource, that grabs the ActiveControl, and pulls the data out of it into the underlying business entity’s property. Since the Save button on the Ribbon calls a SaveData method on the form, we just made SaveData call ForceDataBindingToSource, and then the issue (tab off required so to kick databinding) was solved; or almost.

The TextBox that we use in this application is a subclass of DevExpress TextBox class. We’ve made this subclass implement one of our interfaces, so make it work well with our homegrown databiding mechanism. I noticed that the code in ForceDataBindingToSource wasn’t working on the DX TextBox

Debugging the code I noticed that the ActiveControl was of type TextBoxMaskBox (which does not implement our required interface), even though the control I have on the form is really a subclass of the TextBox class. That puzzled me. I then used the Runtime Object Editor tool to inspect my UI controls during runtime.

aa

The TextBox looked like the one I really had on the form. With a little further inspection, I can actually get to see that there really is a MaskTextBox control within the TextBox:

bb

OK, after having figured that out, I was able to fix my code so to make sure I looked into ActiveControl.Parent (which in the case of a MaskTextBox should be the parent TextBox), and there I can find what I’m looking for.

So that fixes the problem of the user having to tab off the field in order to cause databinding to kick in.

But wait, there’s more. Remember I said I need to synchronize the Ribbon buttons depending on the context? Our business entity raises an event as soon as anything changes on it, so we hooked up into that event to synchronize the Ribbon accordingly. But, again, if the user launches the form and type something into a TextBox, the entity does not get updated until the TextBox loses focus. So, at this point, the user can’t even click on the Save button, which would cause the entity to refresh, since the button is disabled. Chicken and the Egg kind of scenario.

One could say, "well, but that’s easy: just hook up to the TextChanged event and you’re all set!". That is true for TextBoxes, but what about the other controls? I mean, a TextBox has the TextChanged event, a CheckBox has a CheckStateChanged event, a ComboBox has a SelectedIndexChanged event, and so on and so forth. How can I make that generic, then?

Fortunately, in order to implement another feature of this application, I had faced this very same issue (needed a generic event raised whenever any control had its content changed), and solved that by having the classes implement an interface and route the specific events (TextChanged, SelectedIndexChanged, etc.) to a single event defined by the interface.

With that in mind, I was able to hook up that generic event to a single event handler, which calls a FlagAsDirty method on my form, causing the form to go into "dirty mode".

I’m just glad to have found a solution that works in a generic way, and the developers using these classes don’t have to worry about all these nasty issues.

Leave a comment