Development Blog

 Thursday, February 15, 2007
workspace Hosted on Zooomr

1 3007WFP + 2 2007FP = 4960x1600

Need I say more?

by Aaron on Thursday, February 15, 2007 11:14:50 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [3]  |  Trackback
 Monday, February 12, 2007

So I was recently at a good friend's birthday gig. He's actually my old lead at Microsoft. Anyways, some of our friends that are still at Microsoft were at the party and I got a chance to talk to one of them for a while about various things... primarily open source, TDD, Inversion of Control and Mock objects. He was interested in Rhino Mocks and wanted me to email him about it. Instead of just doing that I threw together a good sized email. Here it is (slightly modified):

Good to see you again. As we talked about, there has been quite a shift in the way we write programs... that is a shift towards a much more testable, more maintainable type of programming. I know there are teams at Microsoft that have embraced recent changes... some have gone agile, most use some form of continuous integration, and some have written Inversion of Control containers (the Composite UI Application Block by the patterns & practices group has a container in it), but I'm sure most teams aren't employing all of these practices and could benefit from at least some of them.

In a number of teams, I think that there are a lot of improvements that can be made... even without shipping anything that's open source.

Firstly, you should take another serious look at Test Driven Development. I've attached an interesting study on TDD, and you may want to skim the MS Press book on the subject.

Also, the following blogs have some real good info on it:
Jeremy D. Miller's TDD Posts
Ayende's TDD Posts

A big part of TDD and Unit Testing in general is being able to remove not only your ephemeral dependencies, but also the rest of your dependencies. That way you know, when something fails, exactly what class caused the failure... it's the class being tested. In order to get rid of the dependencies, you need to replace them. In order to replace them, you need two things. The first is a replacement. The second is a method in which to inject the replacement. Mocks and stubs can handle the first task. I mentioned that we use Rhino Mocks:

Ayende's Rhino Mocks Posts

The library is great, it makes for very readable code and it's pretty darn flexible.

The second item can be a bit more complicated. The thing you usually see when class Foo depends on class Bar is this:

class Foo 
{
  private Bar _bar = new Bar(); 

  public string DoStuff()
  {
    return _bar.DoSomeOtherStuff() ? "yes" : "no"
  }
} 

Now if you're going to test Foo, you'll also be testing Bar. You can't avoid that the way it's written. Now, it's good to test Foo talking to Bar eventually, but that's what integration tests are for... not Unit tests. So what do you do? This:

interface IBar { bool DoSomeOtherStuff(); } 

class Foo
{
  private IBar _bar;
  public Foo(IBar bar) { _bar = bar; } 

  public string DoStuff()
  {
    return _bar.DoSomeOtherStuff() ? "yes" : "no"
  }
} 

Subtle difference, but this allows you to throw any implementation of IBar (including a mock) into Foo. That allows you to write a test like this:

[Test]
void DoStuff_WhenBarReturnsTrue_ReturnsYes()
{
  MockRepository mocks = new MockRepository();
  IBar bar = mocks.CreateMock<IBar>();
  Foo foo = new Foo(bar);
  Expect.Call(bar.DoSomeOtherStuff()).Returns(true);
  mocks.ReplayAll(); 

  Assert.Equals("yes", foo.DoStuff());
} 

Now even if Bar changes, or Bar doesn't even exist, this test will still pass.

Here's the definition from Martin Fowler of Dependency Injection/Inversion of Control

Unfortunately, real programs are a lot more complicated than just one class depending on another... dependency chains are generally pretty deep, and one class can depend on 5 classes, each of which depends on 2, each of which has a different lifetime... per web request, transient, singleton, etc. It would be quite a pain if you had to instantiate everything like this:
Foo foo = new Foo(new Bar(new Blah(), Yadda.Instance));

Fortunately, it's not terribly complicated to write a Container that can handle all of this for you... so all you do is something like:
Foo foo = container.Resolve<Foo>();

There are several:

And then I went on to mention how long this mail was getting and that I was going to post it to this blog.

by Aaron on Monday, February 12, 2007 1:33:16 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [1]  |  Trackback
 Sunday, February 11, 2007

It amazes me how often developers lack fundamental competencies. Things that every developer should at LEAST know about, somewhat understand and know the capabilities of (i.e. when they're presented with a problem that is easily solvable using something such as... oh, regular expressions, they can at least google the steps to a solution.) What I'm trying to say is:

Understand and make use of regular expressions whenever it is appropriate.

Unfortunately, if you're reading this blog, you probably read several other blogs, so you've already been exposed to regex's. If that's the case, the tip for you is:

Think of more ways you can use regular expressions, understand them even more, oh and tell a friend/coworker who doesn't subscribe to 30 dev blogs and doesn't understand/make use of regular expressions about them.

There are several resources for regular expressions.

Roy Osherove has come up with some pretty killer tools for regex:

What do you do with them? Well, there are tons of uses for them, but here's a quick list of some of the basic things they're used for:

  • Find things - Duh.
  • Replace things - tons of cool stuff you can do here with and without capture groups. Here's a naive example:
    Foo bar
    Blah yadda
    Etc etc
    // search: (\w*) (\w*) replace: \1 \2 = new \1();
    // becomes:
    Foo bar = new Foo();
    Blah yadda = new Blah();
    Etc etc = new Etc();
    
  • Parse things - obviously we love to parse things.
by Aaron on Sunday, February 11, 2007 10:33:10 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Friday, February 09, 2007

I've seen several people say the following when talking about TestDriven.NET: "It's so easy, just right click, and click run tests!" Maybe I'm just too lazy, but what's easy about moving my hand to the mouse, right clicking, finding the appropriate menu item and clicking it?

Bind a key to Run Test(s) and Run Test(s) with Debugger (I use Ctrl+Shift+R and Ctrl+Shift+D)

Just look for TestDriven.NET.RunTests and TestDriven.NET.Debugger in your keyboard settings. I personally use Resharper's Unit Testing feature (except in our 32bit apps on our x64 machines... they're still fixing that bug), but it's all the same. Bind a key to it. Real easy to finish up a test, hit Ctrl+Shift+R, and away you go. No arm movement required!

by Aaron on Friday, February 09, 2007 4:46:23 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [2]  |  Trackback

I've mentioned several tools that we use here, many of which cost money.  We're very lucky here that we can have most of the tools that we want, I know it pains the check writers--"What? Another $300s per dev?!?!" but thankfully they understand that it helps us immensely. I can't help but notice that occasionally people will mention on their blogs that they really like a tool, but that their company won't buy it for them. I think that usually, that shows a bit of shortsightedness in their management.

Developers are expensive and impatient. Good developers are often even more expensive and even more impatient. Tools help developers write more code faster, better, and with less distraction. We'll use ReSharper as an example to try and calculate true cost of the tool.

Let's say a developer's salary is $60,000 per year, that's about $240/day, or $30/hr. Say you build 10 times in an hour, half those times, you accidently typo'd something so you have to rebuild. We'll say fixing/rebuilding costs you 2 minutes per hour. That's 16 minutes per day or $8/day, $40/week, or about $2000/year. All for losing 2 minutes per hour. It's worse than that too, because 2 minutes is a gross exaageration, and that 2 minutes is during a developer's most productive time... the time they actually spend producing.

Now what if, for $300 you could have something that would warn you of impending build errors, so that you could fix them before you actually built? What if it had keybindings (I use Ctrl+Shift+N and Ctrl+Shift+P) to skip to the next error so you can quickly correct it? What if it saved you not only those 2 minutes per hour, but also gave you several other nifty features that saved you time with navigating, formatting, and several other things. Would you spend $300 to save $2000 per year? I would hope the answer is yes. Many other tools share this same productivity boost to cost ratio.

Does this mean developers should have carte blanche for tools? I don't think so. There still needs to be some filter in place, some time for evaluation, and someone who is in tune with both a developer's need for a tool and the company's need not to spend money senselessly, but please, managers, seriously consider requests for tools.

by Aaron on Friday, February 09, 2007 4:33:41 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [2]  |  Trackback
 Tuesday, February 06, 2007

This goes hand in hand with the first tip, so I figured I should post it now.

Get Gaston Milano's Cool Commands 4.0 and bind a key to Collapse All Projects (I use Ctrl+Alt+C)

There are plenty of other useful gems in CoolCommands (e.g. copy/paste project reference is very useful), but the one I use several times a day is Collapse All Projects. If you've got 40 projects, collapsing them all makes selecting the 36 projects you want to unload much easier.

by Aaron on Tuesday, February 06, 2007 8:45:14 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [2]  |  Trackback

I don't like waiting for things. I don't like typing the same thing over and over again for days, weeks or even months on end. I do as much as I can to speed my production of code up. I want the bottleneck to be in my mind, not in my fingers or my cpu. I figured I'd share some of the things I've learned along the way. Hopefully, a few of the tips will grab your interest and make coding just a little bit less tedious for you. So without further blathering, onto the first tip.

Bind keys to Unload Project and Reload Project (I use Ctrl+Alt+U and Ctrl+Alt+R) and liberally unload projects you aren't mucking with.

This may not apply to you, but here at Eleutian we have about 40 projects to build. Client, server, tools, shared libraries, generators, preprocessors, etc and of course tests for all of them. If you have all 40 projects open, just the dirty check during a build can take up a good amount of time. Generally you're only working on a few projects at a time, so go ahead and unload the rest (you can shift and ctrl select multiple projects to unload or reload). Every build you do (if you're doing TDD, you're dong several) will take significantly less time. Less time between build/test runs is a huge win. Adding the keybinding just saves you from fishing through the 100 item project context menu.

by Aaron on Tuesday, February 06, 2007 8:36:42 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [1]  |  Trackback
 Friday, February 02, 2007

As promised, here's the plugin I was talking about and the Rhino Mocks templates.

Rhino Mocks Templates - Import these in your Template config.

Plugin - Drop this in your "%PROGRAMFILES%\Developer Express Inc\DXCore for Visual Studio .NET\2.0\Bin\Plugins" Oh, and yeah I know it's named after only one of the commands in there, but I was too lazy after I added the other commands to rename the project. You'll see the new commands in the Template configuration in the Command dropdown.

Plugin Source - I know, not the source you want from us right now and it's pretty ugly, but it's a start, right?

by Aaron on Friday, February 02, 2007 6:00:18 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  |  Trackback

I mentioned before that we love templates in CodeRush and that they're incredibly customizable. I wanted to give a few examples of that and share one of the plugins I wrote for it.

We use Ayende's Rhino Mocks quite a bit. We're also lazy, so I came up with a set of templates for it:

  • tfm - Expands to a TestFixture that includes a MockRepository already.
  • scm/sdm - Takes whatever is in your clipboard and expands to this:
    someClass = _mocks.CreateMock<SomeClass>();
  • =cm/=dm - Similar to scm/sdm, but for when you don't have anything in your clipboard
  • mu/mo - Creates a using(_mocks.[Un]ordered()) block
  • mra - ReplayAll
  • mv/mva - Verify or VerifyAll
  • ec - Expect.Call().Return();

One thing I noticed while I was using these is that sometimes I wanted to use them after I'd already written some code that would be in the expansion... for example, say I've already got a class called SomeClassTests but I want to add the TestFixture attribute, add the MockRepository instance variable, etc. Before I had to delete the class and do a tfm on a blank slate. Instead, I spent a few minutes writing a template command plugin that allows you to add an attribute to the class your cursor is in. That enabled me to do what you see in the video below.

Also, say I've already typed the method I was going to set a rhino expectation on. Normally, I'd just have to go to the beginning of the line, type Expect.Call(, go to the end of the line, type the rest. So to solve this, I wrote a few commands: DeleteSemicolon (this one seems a bit buggy w/ the latest CodeRush), GotoBeginningOfLine, and GotoEndOfLine. Now ec, ae, an, ann, etc can all be written to add code around code I've already written as you'll see in the video below.

Bear with me on this video, it's my first attempt at something like this. If anyone can suggest something better than YouTube and a screen recorder for stuff like this that's still free, I'd appreciate it. I don't like being limited to 320x240.

Also, the astute will notice that I'm not running Resharper on this machine. This is my home machine and once again I'm not quite sure about the stability of it (it likes to crash every time I close VS, it breaks some autocomplete scenarios, etc). There are some autocomplete issues in this video, but i think that's just because I had multiple classes named the same thing in this project.

I tried to go slowly so that you can see the templates before I expand them so that hopefully you can get a feel as to how easy it is to write code when you've got templates this powerful. I'm going to upload the source for the plugins as well as my Rhino Mocks templates a bit later today.

by Aaron on Friday, February 02, 2007 10:04:00 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [1]  |  Trackback
 Tuesday, January 30, 2007

I figured I might as well continue on the string literal kick I started with my last post and talk about another situation where we've eliminated string literals. Take the following code from inside a MonoRail action method:

PropertyBag["User"] = ourUser;
PropertyBag["TwoStates"] = new string[] { "WA", "CA" };
PropertyBag["IsAdmin"] = true;

String literals, used as keys into dictionaries carry a cetain degree of code smell (for us) and we try to avoid them. It reminds me too much code that does something similar, but in the opposite direction:

int id = Int32.Parse(this.Params["id"])

Thankfully, this kind of code is eliminated when using MonoRail and its SmartDispatchController. We found ourselves thinking of how the same code would look in a SWF application. We would be populating views, only those views would be interfaces that the various forms/controls implemented. Well, this is exactly what we wanted in MonoRail, to wrap the PropertyBag with an interface!

After a few hours playing with Reflection.Emit, I had a code generator that would take an interface:

public interface IEditMyProfileView
{
  string Name { get; set; }
  DateTime Birthday { get; set; }
  IList<TimeZone> TimeZones { get; set; }
}

And produce a class like the following:

public class EditMyProfileViewPropertyBagManipulator : IEditMyProfileView {
  private IDictionary _bag;

  public EditMyProfileViewPropertyBagManipulator(IDictionary bag) {
    _bag = bag;
  }

  public string Name {
    get { return (string)_bag["Name"]; }
    set { _bag["Name"] = value; }
  }
  public DateTime Birthday {
    get { return (DateTime)_bag["Birthday"]; }
    set { _bag["Birthday"] = value; }
  }
  public IList<TimeZone> TimeZones {
    get { return (IList<TimeZone>)_bag["TimeZones"]; }
    set { _bag["TimeZones"] = value; }
  }
}

This has the advantage of keeping our interactions with the PropertyBag as type safe as they can be. Changing the interface, breaks the build. Where as changing the type of a value inserted into the PropertyBag will (hopefully) only break tests if even that. This is another example of us trying to turn run-time failures into compile-time failures.

This kind of thing also makes tests more elegant. Instead of:

Assert.Equals("Jacob", PropertyBag["Name"]);

In our controller tests, we can continue to leverage the use of RhinoMocks to ensure the views are properly initialized:

using (_mocks.Unordered()) {
  _view.Name = "Jacob";
}
_mocks.ReplayAll();
_controller.Action();
_mocks.Verify(_view);

All we've done here is created a mock from the view interface, rather than emitting the wrapper class. Again, another added benefit is if the view changes, compiling the tests will also break. The sooner things break after a change the better, and the build is pretty soon. Although, with ReSharper, it's nice to see red squiggles appear as that's even sooner.

by Jacob on Tuesday, January 30, 2007 8:31:07 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [1]  |  Trackback