News

NOTE:

My blog has officially moved to Los Techies Please update your bookmarks. I have already updated the Feedburner RSS/ATOM feeds.

Reminder: My blog has moved

Add Comment | Apr 30, 2008

Just in case you're still reading this feed and not my Feedburner feed, I'm no longer posting to this feed.  If you're still reading this feed, you've been missing a lot!  I'd like to invite you to check out my current blog location (http://chadmyers.lostechies.com) as well as subscribe to my Feedburner Feed so we don't have to go through moving pains anymore.

My Feedburner feed is here: http://feeds.feedburner.com/ChadMyersBlog

Also, I'm now part of the Los Techies professional blogging group. I'd like to invite you to subscribe to their feed as well:  http://feeds.feedburner.com/lostechies

Thanks!

Chad Myers

Austin TDD CodingDojo Signup

Add Comment | Jan 10, 2008

(cross-posted from my new blog at http://www.lostechies.com/blogs/chad_myers)


The details of the Austin TDD CodingDojo event have been finalized and the sign up form is now online.

Signup (opens in new window):

http://austintddcodingdojo.wufoo.com/forms/austin-tdd-codingdojo-signup/

Details:

Who

You! We hope to have a good mix of experts and novices and everyone in between. The hope is that everyone will be forced to challenge their practices and ideas and glean insight from the ideas and practices of others. 

What

.NET, C# based group coding session in the prescence of peers and to suffer review, criticism and suggestions with the goal of gaining better experience and understand of the practice of Test-Driven Development.  The style will be similar to the 'CodingDojo' (opens in new window).

When

Saturday, February 9th, 2008 from 8:00am until 12:00pm.  Optional networking will follow and I'm sure a few people will probably go out to lunch together afterwards to share ideas, reflect, and network.

Where

TOPAZ Technologies, Inc. is graciously hosting the venue for us. Thanks!
Their address is:
9601 Amberglen Blvd.
Suite 140, Bldg G
Austin, TX 78729

Space is limited to the first 30 registrants.

Use Google Map or Windows Live Maps for directions

NOTE: We'll set up in the front training room. Please no food in the training room. There will be a break room where food can be eaten.

Misc

We're trying to arrange breakfast tacos and/or doughnuts and there should be refreshments (coffee, tea, cocoa, water). If anyone wishes to help sponsor/contribute to the food and beverage fund, it would be much appreciated.

For questions, comments, suggestions, gripes, R0l3x or V1/\Gra Spam, please email us: austintddcodingdojo+comments@gmail.com

Joining the Donkey Side

One Comment | Jan 04, 2008

The wonderful folks over at Los Techies invited me to join the list of their notable and venerable bloggers and I humbly accepted.

If you have subscribed to my Feedburner RSS feed, you should have to do nothing to migrate with me. The new Web URL will be: http://www.lostechies.com/blogs/Chad%5FMyers/

SVN global ignores

Add Comment | Jan 03, 2008

David Wood had a post about global ignore settings with SVN/TortoiseSVN and so I thought I'd post mine, in case it helps anyone:

Bin */Bin bin */bin obj */obj *.suo *.csproj.user *.log *.log.* *.rdl.data *.rptproj.user build */build

Static Reflection using Expression Trees

Add Comment | Dec 31, 2007

Daniel Cazzulino posted a rather interesting use for Expression Trees (he says 'Linq', but it's not really Linq, it's one of the features born out of need from Linq: Expression Trees).

I've had a couple run-ins with situations that this could've easily solved and I wish I had it back then.

If you have a spare moment or two, check it out, it's pretty cool.

The expression tree and delayed execution thing, while very helpful and useful, is a little bewildering at first. I'm familiar with this stuff and I had to do a triple take before I understood what was going on.

I'm not a weather guy

4 Comments | Dec 27, 2007

I thought it went without saying, but apparently there are a few who are confused (and they email me about it):

This is me:

This is *NOT* me:

(CNN Weather Anchor Chad Myers)

I *DO NOT* know how to personally contact the CNN Chad Myers, so please do not ask me.

And NO my most recent addition to my family is NOT his. Thank you very much.

I hope I don't lose half my readership because of this. Hah!  I wonder why people really thought that Chad Myers was so much into .NET development. "Wow," they must've thought, "he's an accomplish meteorologist *AND* can hold his own in a C# wet paper bag competition!

What do newborns dream about? (OT)

5 Comments | Dec 20, 2007

Sorry for another OT post, but the other day I was watching my new son, David, sleep. I could tell he was dreaming because he would smile, squeal, kick his legs, grimace, and make other emotional response-type movements (beyond the normal spastic-type movements that newborns normally make).

I've noticed this with all my babies and it got me wondering, "What could he possibly be dreaming about that would make him laugh?"  What possible life experience or frame of reference or memory could this (then) day-old baby have that would cause him to dream something that would cause him to laugh?

Another curious fact is that, so far, he has not yet laughed while awake.  I've only ever seen him smile and laugh in his sleep.

Strange, huh?

What do you think he's dreaming about? Does anyone have any explanation?  All answers are safe, by the way, including scientific, atheistic, and theistic (any faith tradition). Please don't debate religion here though, just post what you believe they dream about and let everyone have their say.

My personal belief:  They see angels. 

It's a Boy!

10 Comments | Dec 16, 2007

David Joseph Myers was born yesterday (15-DEC-2007).  He was a whopping 9lbs 13oz (4.45kg) and 22 inches (55.9cm).

Everyone is happy and healthy!  His face got a little bruised up on the way out, but his color is returning nicely.

Thank you everyone for your thoughts and prayers during some of the scares in the pregnancy. Everything turned out just fine.

Sincerely,

Chad

Moore on the Anonymous Delegate Approach

6 Comments | Dec 15, 2007

Mike Moore raised a good question on my previous post about (ab)using anonymous delegates to achieve JavaScript-like dynamic class interface  functionality:

You can swap out the expected return value when using this for testing, but can you actually implement any useful, state-changing functionality using anon delegates?

So I decided to try this out and I was able to do most of what he's asking for, with one caveat.

Member Accessibility Rules Still Apply

First, I should say that the rules of member visibility still apply with respect to accessing, for example, private member variables from an external caller. That is, if you 'override' one of the anonymous delegate pseudo-methods from outside the class definition itself, you will not be able to access the private member variables inside that class.

Consider the following class:

public class WellWaterSource : WaterSource
{
    private bool _isDrought;

    public WellWaterSource()
    {
        TakeSome = () => { return !_isDrought; };
    }
}

If I want to override TakeSome on WellWaterSource from outside the WellWaterSource class definition, I won't be able to access the _isDrought member.  This will limit the amount of stuff you can do with this approach, for sure. So you would definitely want to avoid private members for sure, and internal and protected members would require serious consideration. For example:

public class SomeOtherClass
{
    public SomeOtherClass(WellWaterSource src)
    {
        src.TakeSome = () => { return true && src._isDrought; };
    }
}

This will result in a compiler error:

error CS0122: WellWaterSource._isDrought' is inaccessible due to its protection level

Accessing Instance Members From Class Prototype Requires Compromise

One other downside of this approach is that, in order for you to access instance members from the class-level prototype, you have to pass in the 'this' reference to the delegate.

Consider the following class:

public class SmallWellWaterSource : WellWaterSource
{
    public static WellTakeSomeFunc TakeSomeWellWaterPrototype =
        w => { w.WaterRemaining--; return (w.WaterRemaining > 0); };

    public int WaterRemaining { get; set; }

    public SmallWellWaterSource()
        : base()
    {
        WaterRemaining = 100;
        TakeSome = () => { return TakeSomeWellWaterPrototype(this); };
    }
}
public delegate bool WellTakeSomeFunc(SmallWellWaterSource source);

You'll notice that we have to pass in the 'this' reference in the c'tor in order to allow the static prototype to access/manipulate the WaterRemaining value. This isn't horrible, and would be a common pattern, but it's some extra work you have to do that you wouldn't (obviously) in other languages like JavaScript, Ruby, etc.

This isn't just .NET 3.5

Mike made a comment about not having .NET 3.5 installed yet. I just wanted to point out that none of this stuff is .NET 3.5-specific. You can do it with .NET 2.0, it's just uglier since we don't have lambda expressions. For example, we could do this:

public class WaterSource
{
    public static TakeSomeFunc TakeSomePrototype = delegate { return true; };

    public TakeSomeFunc TakeSome = delegate { return TakeSomePrototype(); };

    public delegate bool TakeSomeFunc();
}

Last Comment

Finally, Mike says:

All this work to get around static typing...

I know, man. I know. I can't use Ruby at work, though (heck, I can't even use .NET 3.5 at work yet), so we can at least try to explore how to bend C# to our will as much as possible :)

Dynamic-like Typing using Anonymous Delegates in C#

9 Comments | Dec 15, 2007

Background: Changing Class and Instance Members At Runtime

One of the nifty things about dynamic languages like JavaScript, Ruby, and others is the fact that you can manipulate aspects of class prototype information (i.e. the Class itself -- its interface) of all instances of that class, as well as individual instances.

For instance, we can do something like this in JavaScript:

function Pegleg(typeName)
{                    
    this.name = typeName;
}

var hungry = new Pegleg("I'm hungry");
var thirsty = new Pegleg("I'm thirsty");

// Add a new method to all current and future instances
Pegleg.prototype.ToPirateSpeak = 
    function(){ return this.name + ", Arrr!"; }

document.writeln(hungry.ToPirateSpeak() + "<br/>");
document.writeln(thirsty.ToPirateSpeak() + "<br/>");

// Add a new method to this specific instance
hungry.ToAngryPirate = 
    function(){ return "Avast, " + this.name + ", Yarrr!"; }
        
document.writeln(hungry.ToAngryPirate() + "<br/>");

Which will print out:

I'm hungry, Arrr!
I'm thirsty, Arrr!
Avast, I'm hungry, Yarrr!

This is pretty handy, especially when doing it carefully and with great consideration using a framework like Prototype to help you stay focused on good OO-like design principles. This sort of thing comes in pretty handy when doing unit tests, as you don't have go through a lot of hoops to do mocking in you unit tests, since you change the interface on the class-under-test and its dependencies at run-time/test-time.

Of course, this sort of thing isn't possible in C#, which is why we need to use interface-based programming. Well, there's a lot of other good reasons to use interface-based programming in many circumstances, but there are quite a few times where interfaces aren't needed except in order to facilitate mock-based testing.

But wait, all hope is not lost...

We can achieve something similar to this effect in C# by forgoing our current understanding of how methods work in C# classes. By using anonymous delegates, we can achieve similar capabilities which let us perform mock-based testing without having to clutter up all our classes with interfaces.

Consider the following class:

public class Tree
{
    private WaterSource _waterSource;
    private NutrientSource _nutrientSource;

    public Tree(WaterSource waterSource, NutrientSource nutrientSource)
    {
        _waterSource = waterSource;
        _nutrientSource = nutrientSource;
    }

    public int Height{ get; set; }
    public virtual bool TakeWater()
    {
        return _waterSource.TakeSome();
    }

    public virtual bool TakeNutrients()
    {
        return _nutrientSource.TakeNutrients();
    }

    public virtual void Grow()
    {
        if (TakeWater() && TakeNutrients())
            Height++;
    }
}

This approach isn't bad, but it doesn't leave me a lot of options for unit testing Tree.  If WaterSource.TakeSome() is not a virtual method, then I cannot mock it using something like Rhino.Mocks.  Now my unit tests necessarily have to worry about what WaterSource.TakeSome() will return under any given condition.  This makes for leaky, complicated tests. What I'd like to do is somehow override TakeSome() and provide my own implementation so I can make it return what I want in my unit test to simulate specific known conditions.

Currently, one of the best ways of doing this is to create an interface (i.e. IWaterSource), have WaterSource implement it, and then use a mocked instance of IWaterSource to simulate desired behavior.  But what if I don't want IWaterSource because I'll never use it for anything else?

Perhaps we could try something like this:

BEFORE

public class WaterSource
{
    public bool TakeSome()
    {
        return true;
    }
}

AFTER

public class WaterSource
{
    public TakeSomeFunc TakeSome = () =>{ return true; };
    public delegate bool TakeSomeFunc();
}

Now, with this I can change the implementation of a given WaterSource implementation at runtime. So in my test I can do something like this:

[Test]
public void Should_not_change_height_if_no_water_available()
{
    WaterSource water = new WaterSource();
    NutrientSource nutrients = new NutrientSource();
    Tree tree = new Tree(water, nutrients);
    Assert.That(tree.Height, Is.EqualTo(0));

    // Mock the TakeSome method to return the desired result
    water.TakeSome = () => { return false; };
    tree.Grow();

    Assert.That(tree.Height, Is.EqualTo(0));
}

What about 'prototype' or class-level overrides?

At this point, all we've done is addressed the instance-level problem, we haven't touched on the class-level problem (the '.prototype' situation in JavaScript parlance).

If we change our TakeSome definition to call a static, class-level prototype implementation, then we can achieve a class-level override of the method, but still allow for individual method-level overrides:

public class WaterSource
{
    public static TakeSomeFunc TakeSomePrototype = () => { return true; };

    public TakeSomeFunc TakeSome = () => { return TakeSomePrototype(); };

    public delegate bool TakeSomeFunc();
}

Now we can test changing all instances, and changing an individual instance and ensure that they work properly:

[Test]
public void This_is_a_sample_test_and_not_what_I_would_normally_do()
{
    WaterSource water1 = new WaterSource();
    WaterSource water2 = new WaterSource();
    NutrientSource nutrients = new NutrientSource();

    Tree tree1 = new Tree(water1, nutrients);
    Tree tree2 = new Tree(water2, nutrients);

    // Change all instances and mock the result
    WaterSource.TakeSomePrototype = () => { return false; };

    tree1.Grow();
    tree2.Grow();

    Assert.That(tree1.Height, Is.EqualTo(0));
    Assert.That(tree2.Height, Is.EqualTo(0));

    // Now change the one instance back, and try again
    water2.TakeSome = () => { return true; };

    tree1.Grow();
    tree2.Grow();

    Assert.That(tree1.Height, Is.EqualTo(0));
    Assert.That(tree2.Height, Is.EqualTo(1)); //<-- It Grew!
}

What about inheritance?

This method can still work even in inheritance scenarios. Consider the following SaltWaterSource subclass:

public class SaltWaterSource : WaterSource
{
    public SaltWaterSource()
        : base()
    {
        // Override default implementation
        TakeSome = () => { return WaterIsAvailable(); };
    }

    public bool WaterIsAvailable()
    {
        // Salt Water is only avilable on Tuesday, I don't know why
        // this is what the customer asked for
        return (DateTime.Now.DayOfWeek == DayOfWeek.Tuesday);
    }
}

And it works in the test:

[Test]
public void This_is_a_sample_test_and_not_what_I_would_normally_do()
{
    SaltWaterSource saltWater = new SaltWaterSource();
    NutrientSource nutrients = new NutrientSource();

    Tree tree = new Tree(saltWater, nutrients);

    saltWater.TakeSome = () => { return false; };

    tree.Grow();

    Assert.That(tree.Height, Is.EqualTo(0));
}

One problem with this approach is that I won't be able to override the prototype TakeSome for ONLY SaltWaterSource instances. If I want to add more prototype-ability to SaltWateSource implementations, I could do something like this:

public class SaltWaterSource : WaterSource
{
    public static TakeSomeFunc TakeSomeSaltWaterPrototype =
        () => { return (DateTime.Now.DayOfWeek == DayOfWeek.Tuesday); };

    public SaltWaterSource()
        : base()
    {
        TakeSome = () => { return TakeSomeSaltWaterPrototype(); };    
    }
}

Note that I didn't have to redefine TakeSome. I was able to override it via the c'tor and thus preserve the polymorphism aspect of C# classes.

And then our test looks about the same, except just with a SaltWaterSource:

[Test]
public void This_is_a_sample_test_and_not_what_I_would_normally_do()
{
    SaltWaterSource water1 = new SaltWaterSource();
    SaltWaterSource water2 = new SaltWaterSource();
    NutrientSource nutrients = new NutrientSource();

    Tree tree1 = new Tree(water1, nutrients);
    Tree tree2 = new Tree(water2, nutrients);

    // Change all instances and mock the result
    SaltWaterSource.TakeSomeSaltWaterPrototype = () => { return false; };

    tree1.Grow();
    tree2.Grow();

    Assert.That(tree1.Height, Is.EqualTo(0));
    Assert.That(tree2.Height, Is.EqualTo(0));

    // Now change the one instance back, and try again
    water2.TakeSome = () => { return true; };

    tree1.Grow();
    tree2.Grow();

    Assert.That(tree1.Height, Is.EqualTo(0));
    Assert.That(tree2.Height, Is.EqualTo(1)); //<-- It Grew!
}

Workaround for ASP.NET MVC Controllers

One nifty side-effect of this method is that we can now effectively test controllers in the ASP.NET MVC framework without having to do the subclass-for-test approach (as illustrated by Phil Haack on his blog) which is currently required due to a design flaw in the RenderView() method implementation in the Preview release of the MVC bits that are available at the time of this writing.

I prefer not having to subclass my Controllers just to test them, so I was looking for a way to keep the controllers sound without having to contort too horribly in order to make them testable. I came up with this adaptation to the standard HomeController that comes with every new "ASP.NET MVC Application" project wizard in Visual Studio 2008:

public class HomeController : Controller
{
    public RenderViewProc CallRenderView;

    public HomeController()
    {
        CallRenderView = (v,d) => { this.RenderView(v, d); };
    }

    [ControllerAction]
    public void Index()
    {
        RecipeRepository repo = new RecipeRepository();
        
        CallRenderView("Index", repo.FindAllReceipes());
    }

    [ControllerAction]
    public void About()
    {
        CallRenderView("About", null);
    }
}

public delegate void RenderViewProc(string viewName, object viewData);

 

Incidentally, my RecipeRepository also uses the anonymous delegate instance method approach so that I can mock it for testing as well. So my test ends up looking like this:

[Test]
public void Should_get_list_of_recipes_and_invoke_the_index_action()
{
    bool findAllCalled = false;
    bool valueSet = false;

    HomeController controller;
    // Record
    {
        // Mock the recipe find all method
        RecipeRepository.FindAllRecipesPrototype = () => { findAllCalled = true; return null; };
        controller = new HomeController();
        controller.CallRenderView = (v, d) => { valueSet = true; };

        // Sanity check
        Assert.That(findAllCalled, Is.False);
        Assert.That(valueSet, Is.False);
    }

    // Playback
    {
        controller.Index();
    }

    // Test expectations -- similar to VerifyAll() w/ Rhino.Mocks
    Assert.That(findAllCalled, Is.True);
    Assert.That(valueSet, Is.True);
}

As you can see here, I was able to mock the FindAllReceipes() method and the CallRenderView method to totally negate the RenderView() non-mockable dependency problem.

Likewise, I was able to achieve a similar set of functionality to Rhino.Mocks Expect.Call() record/playback system.  It's not as robust as Rhino.Mocks, but for this purpose it isn't so bad.

What does this all mean?

I'm not sure where to go from here, or what this means. I haven't gone much further than what you see here.  It seems like it solves a lot of the current problems around Interface-explosion and dynamic typing vs. static typing, etc.  I'm sure I've probably missed a death-knell here and I'm curious to know what it would be. Performance? OO-fundamental violation? Compiler confusion?  Any obvious errors that you can see?

I'm going to keep playing with this for awhile and see if I can see any buzz-kills, but so far I'm thinking that this might be a valid approach for certain situations and solving a few specific problems without having to add interfaces to everything