Nerdy tidbits from my life as a software engineer

Thursday, February 26, 2009

Bypassing Constructors With Mock Objects

I was working on a class tonight where I wanted to put some initialization logic in the constructor.  But that logic was not something I wanted invoked in my unit tests.  It was creating a new thread, and I didn’t want the thread actually created within my tests because I wanted to isolate the creation and destruction logic of the thread in one place instead of having lots of unrelated tests validate it as well.

So how do I test this?  Well one option is to take the logic out of the constructor and move it into another method.  Then I can use a partial mock and mock the call.  But that isn’t really preferable in most cases, because now I’m forcing somebody to make an additional method call if they want to use my object properly.  So I’m really not encapsulating behavior very well.  I didn’t like that idea.

And then it occurred to me that there’s really a very simple solution to this problem, and that is to define a protected constructor which does not call the things you want to be avoided in your tests.  Then, you can use a partial mock that calls the protected method instead of the public one, and viola – the real, publically exposed constructor is not called in the tests, but is called in the real world.

So just to illustrate how this works:

public class TestMe
{
    public TestMe()
    {
        // Called by everybody else
    }

    protected TestMe()
    {
        // Called from mock objects
    }
}

I had to make a few minor changes in my mock framework to get this working (just search for NonPublic constructors as well as Public ones).  But I think the results are encouraging.  What I like about this is that it doesn’t expose behavior to anybody, and since only subclasses can call the protected constructor, there’s no real loss of encapsulation.  Sure, somebody else could come along and subclass TestMe, calling the protected constructor instead of the public one.  But  that’s their problem.  If they break the behavior of the parent class in the subclass, well, they’re not doing a very good job of writing object orientated code.

Exception Throwing Lambdas Not Allowed

Apparently, the compiler is unable to resolve this:

public delegate T ReturnHandler<T>();
...
public void Whatever<T>(ReturnHandler<T> handler)
{
   ...
}
...
Whatever(() => throw new Exception("Doesn't work"));

You will end up getting all sorts of nasty syntax errors.  Why?  I’m not sure I understand why this can’t be parsed properly.  I suppose the lexer isn’t looking for the throw keyword when it scans the source code.  What is it looking for?  I suppose identifiers, “return”, numbers / constants (IE, true / false), and “{“.  But apparently not “throw”.  That’s kind of a bummer, and I don’t see why it can’t easily parse that expression properly.

To get around this limitation, you need to do this:

Whatever(() => { throw new Exception("Should not be necessary...but it is"); });

Problems Paying For Internet Access

I was on vacation at Whistler this weekend.  Because I can’t live without the internet, I brought my laptop with me thinking that there was free internet at our condo.  I found out quickly that yes, there was internet access….but no, it was not free.

Being the miserly person that I am, I decided not to pay $10.00 to get on the internet just to check my email and read the news.  I can wait a couple of days.  But a friend of mine who came with me needed to send an email, and decided to fork over the 10 bucks.  Since he paid for a username / password, I mooched off of his purchase and spent some time online.

When I got back home to Seattle, I had this strange problem with my computer where it was connecting to my home network, but I only had local access.  At first I figured it was just Comcast doing there usual thing where they take your internet down for no reason.  But when I discovered that my desktops connection worked fine, it occurred to me that the pay-for-your-internet-access script at Whistler did something funky to my machine and it couldn’t connect to the internet any more.

But what could it have done?  I didn’t run an ActiveX control.  I didn’t install any VPN software.  I didn’t do anything funky to my connection other than type in a username and password in a website.  Nope.  Somehow, via voodoo black magic, I ended up on the internet at Whistler, and some script altered my network settings to make that happen.  And of course, the script didn’t have the intelligence to revert its changes when I was no longer connecting through their network.

First I checked my internet connection settings.  I figured they were redirecting me to a proxy server.  But no – that wasn’t it. 

So then I checked the properties of my Wireless Connection and checked the properties on my TCP/IPv4 protocol.  And that’s when I discovered the problem: whatever happened when I logged into the Whistler pay-for-your-internet system changed my settings from “Obtain DNS server address automatically” to “Use the following DNS server addresses”, which of course had some IP address that’s only valid on their network and cannot be resolved once you leave.

So that’s how those systems work.  When you log in, they must somehow change your TCP/IP settings to point to a custom IP address to resolve DNS names.  This scares me for several reasons.  First, how on earth can a website change your network settings?  That seems like a clear security violation to me.  I can’t tell how they got away with it.

Second, it’s clearly irresponsible to change people’s network settings without a) telling them, and b) reverting them later on.  I’m pretty knowledgeable about this sort of thing – but what about grandma?  Most people would end up calling Comcast and complaining that their internet doesn’t work any more.  And we all known how those phone calls end up.  I can only imagine how much time is wasted cleaning up people’s TCP/IP settings from these bad systems.

Now the other thing: once you know their little trick, what’s stopping somebody from just manually setting their DNS server in their network settings and bypassing the $10.00 fee?

Wednesday, February 18, 2009

Singleton vs Repository

The Singleton pattern is probably one of the most common design patterns you’ll see over your career.  Understandably.  But a while ago, I read through Martin Fowlers’ excellent Patterns of Enterprise Application Architecture and discovered the very simple repository pattern – and I’ve found myself using that instead more and more frequently.  So what’s the difference and why do I like it so much?

I don’t know; much if it is semantics I suppose.  But what I like about the Repository pattern is that it’s hiding the singleton nature of a class from it’s consumers.  There’s something about that implementation that, to me, looks very elegent.  In the end, the two patterns accomplish the same thing – but one ends up being just a little bit more convenient to invoke than the other.  And there are benefits to making calls convenient to the consumer of a class.

You might do something like this for a singleton:

public class Singleton
{
    /// <summary>
    /// This is the one and only instance of the singleton.
    /// </summary>
    private static Singleton mInstance;

    /// <summary>
    /// The static constructor creates the one and only instance.
    /// </summary>
    public static Singleton()
    {
        mInstance = new Singleton();
    }

    /// <summary>
    /// Creates the singleton.
    /// </summary>
    private Singleton()
    {
        ...
    }

    /// <summary>
    /// Returns an instance to the singleton.
    /// </summary>
    public static Singleton
    {
        get
        {
            return mInstance;
        }
    }    

    /// <summary>
    /// Access some property.
    /// </summary>    
    public bool SomeValue
    {
        get;
        set;
    }

}

Now when you want to get the one and only value of SomeValue, you do this:

...
if(Singleton.Instance.SomeValue)
{
    ...
}

Now with the repository pattern, you can access singleton-like properties and methods as though the object you were accessing was just a regular object with static methods and properties.  Here’s what the same object looks like as a Repository:

public sealed class Repository
{
    /// <summary>
    /// This is the one and only instance of the repository.
    /// </summary>
    private static Repository mInstance;

    /// <summary>
    /// This bool contains some interesting value.
    /// </summary>
    private bool mSomeValue;

    /// <summary>
    /// The static constructor creates the one and only instance.
    /// </summary>
    public static Repository()
    {
        mInstance = new Repository();
    }

    /// <summary>
    /// Creates the singleton.
    /// </summary>
    private Singleton()
    {
        mSomeValue = true; // or whatever
    }   

    /// <summary>
    /// Get / set some property.
    /// </summary>    
    public bool SomeValue
    {
        get
        {
            return mInstance.mSomeValue;
        }
        set
        {
            mInstance.mSomeValue = value;
        }
    }

}

What’s nice about this is that you no longer need to access the Repository’s one and only instance via the Instance property.  This really helps with readability.  To get the one and only value of SomeValue, you can simply do this:

...
if(Repository.SomeValue)
{
    ...
}

In exchange for this syntax convenience, you are now required to write a bit more plumbing code.  You also, admittedly, lose a bit of flexibility with unit testing.  For instance, one way that I’ve always liked to mock out singletons is by doing something like this:

public interface ISingleton
{
    bool SomeValue
    {
        get;
        set;
    }
}

public class Singleton : ISingleton
{
    /// <summary>
    /// This is the one and only instance of the repository.
    /// </summary>
    private static Singleton mInstance;

    /// <summary>
    /// The static constructor creates the one and only instance.
    /// </summary>
    public static Singleton()
    {
        mInstance = new Singleton();
    }

    /// <summary>
    /// Creates the singleton.
    /// </summary>
    private Singleton()
    {
    }   

    /// <summary>
    /// Get / set some property.
    /// </summary>    
    public static Singleton Instance
    {
        get
        {
            return mInstance;
        }

    }

    /// <summary>
    /// Get / set some property.
    /// </summary>    
    public bool SomeValue
    {
        get;
        set;
    }

}

public class Consumer
{
    public Consumer()
    {
        this.SingletonInstance = Singleton.Instance;
    }

    public ISingleton
    {
        get;
        set;
    }
}

Now in your unit tests, you can create a mock on an ISingleton object, inject it into your code, and test methods on the Consumer class.  I haven’t really looked into how to test repositories – I’m sure there’s a way, but unfortunately, static methods don’t count against an interfaces implementation.  And that’s a bummer, because I figure you’d have to use some sort of wrapper class around a repository so that it could be mocked and tested.

Something to think about.

Thursday, February 5, 2009

Mimics In Action

After months of anticipation, dynamics have finally made it into a stable drop of Visual Studio 2010.  And that’s given me an opportunity to play around with the new 4.0 framework and tested out my idea of using mimics to unit test classes that have non-virtual methods.

First the good news: it works! Mimics, as a concept, solve the problem of unit testing objects that lack virtual methods.  This is very exciting.  I’m still trying to play around with the API to see how to fit the concept into my mock framework, but that shouldn’t be too hard.  The important thing is that I have a proof of concept that works.

Here’s a code sample.  Say you have a WPF window (markup first, then code):

<Window x:Class="WpfApplication1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Hello World!"
        mc:Ignorable="d"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Height="105"
        Width="181">
    <Grid>
        <CheckBox Content="Say Hello?"
                  Height="16"
                  Margin="12,12,0,0"
                  Name="mCheckBox"
                  VerticalAlignment="Top"
                  HorizontalAlignment="Left"
                  Width="120" />
        <Button Content="Go Ahead"
                Height="23"
                HorizontalAlignment="Left"
                Margin="12,34,0,0"
                Name="button1"
                VerticalAlignment="Top"
                Width="75"
                Click="OnButton1Clicked" />
    </Grid>
</Window>

using System;
using System.Windows;
using System.Windows.Controls;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            this.CheckBox = mCheckBox;
        }

        public dynamic CheckBox
        {
            get;
            set;
        } 

        /// <summary>
        /// Called when button1 is clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnButton1Clicked(object sender, RoutedEventArgs e)
        {
            if (this.CheckBox.IsChecked == true)
            {
                // Test whatever ...
            }
        }

    }
}

I can now write a unit test that does this:

/// <summary>
///This is a test class for Window1Test and is intended
///to contain all Window1Test Unit Tests
///</summary>
[TestClass]
public class Window1Test
{
    /// <summary>
    ///A test for OnButton1Clicked
    ///</summary>
    [TestMethod()]
    public void OnButton1ClickedTest()
    {
        Window1_Accessor window = new Window1_Accessor(new PrivateObject(new Window1()));
        CheckBoxMimic mimic = new CheckBoxMimic();
        mimic.IsChecked = true;
        window.CheckBox = new CheckBoxMimic();
    }

    // Imagine this class was auto-generated and fit into a mock framework:
    private class CheckBoxMimic
    {
        public bool? IsChecked
        {
            get;
            set;
        }
    }

}

That’s pretty awesome, isn’t it?  Where as before .NET 4.0, the IsChecked property was un-mockable, we finally have a way to unit test GUI’s using mock frameworks.  That just tickles me happy.

So, now the bad news.  As I’ve blogged about before, the problem with dyanamics is that there is no strong-typing involved by nature, which means you won’t get a compiler error if you do something silly like invoke a bogus method on the CheckBox property.  I’ve already run into this problem.  Not having auto-complete is an issue, and there’s just no getting around the fact that you will have runtime errors if you adopt this development method in order to unit test your GUI’s.  That’s a problem.  Plus the fact that invoke dynamics is clearly less efficient than calling a compiler-bound method directly.  I can see the potential for wide-scale abuse here by terrible developers.  Let’s hope we’re not unleashing some terrible nastiness on the world.

Anyways, I have, in fact, developed a decent – though not ideal – solution to the intellisense / compile time problem.  And that solution uses preprocessor values to do some fun compile-time switching for you.  Here’s how the replaced code looks:

#if DEBUG
#define USING_MIMICS
#endif

using System.Windows;
using System.Windows.Controls;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            this.CheckBox = mCheckBox;
        }

#if USING_MIMICS
        public dynamic CheckBox
        {
            get;
            set;
        } 
#else
        public CheckBox CheckBox
        {
            get;
            set;
        }
#endif

        /// <summary>
        /// Called when button1 is clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnButton1Clicked(object sender, RoutedEventArgs e)
        {
            if (this.CheckBox.IsChecked == true)
            {
                // ...
            }
        }

    }
}

Nobody likes preprocessor directives.  But this does solve the problem.  When writing code in the event handler, you can simply comment out the #define USING_MIMICS line at the top of the file.  That way, the properties are evaluated by their strong types.  Then, when you’re ready to test, you can uncomment the line and compile your test – which now looks like this:

#if DEBUG
#define USING_MIMICS
#endif

using WpfApplication1;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Windows;

namespace TestProject1
{   
    /// <summary>
    ///This is a test class for Window1Test and is intended
    ///to contain all Window1Test Unit Tests
    ///</summary>
    [TestClass()]
    public class Window1Test
    {

#if USING_MIMICS

        /// <summary>
        ///A test for OnButton1Clicked
        ///</summary>
        [TestMethod()]
        public void OnButton1ClickedTest()
        {
            Window1_Accessor window = new Window1_Accessor(new PrivateObject(new Window1()));
            CheckBoxMimic mimic = new CheckBoxMimic();
            mimic.IsChecked = true;
            window.CheckBox = new CheckBoxMimic();
        }

#endif

        private class CheckBoxMimic
        {
            public bool IsChecked
            {
                get;
                set;
            }
        }

    }
}

Now, to simplify the preprocessor conditionals, one thing you can do is create a new build configuration.  I made one called “Unit Testing”, where the only difference between it and debug is that it defines the USING_MIMICS constant in the build configuration in each csproj file.  That way, you can avoid putting the #if statement at the top of every file you want to use mimics on.  And the act of switching from the “Unit Testing” configuration back to Debug or Release will tell you – instantly – if your code compiles or not. 

It’s not perfect, but it’s one way to verify that dynamics will work at runtime even if the methods are invoked dynamically.

Monday, February 2, 2009

Nested Classes

There’s really nothing I hate more than non-private inner classes.  In most cases, when you write something like this:

public class Whatever
{
  public void SomethingInteresting()
  {
   SomeNamespace.SomeClass c = new SomeNamespace.SomeClass();
   ...
  }
}

You can make your life easier by using the namespace:

using SomeNamespace;

public class Whatever
{
  public void SomethingInteresting()
  {
   SomeClass c = new SomeClass();
   ...
  }
}

This is particularly nice when you get some long-winded namespaces and class names.  There’s nothing more annoying to me to see your code cluttered with all sorts of useless garbage, like:

public void SomethingInteresting()
{
  Some.Very.Long.Namespace.SomeClassNameThatIsLong c = new Some.Very.Long.Namespace.SomeClassNameThatIsLong()
}

Ask yourself, is it really necessary to spell out the entire qualified name all over the place?  All this is really doing is killing the readability of your code for no tangible benefit.  Remember that if you are really concerned with clarifying the location of a particular class you can use the namespace but still write the fully qualified name.  At least in those cases you have the option, and you are not forcing your users to style their code one way or the other.

Now let’s figure that you decide you like using public inner classes, for some reason that makes no sense to me.  So you have something like this:

namespace SomeNamespace
{
  public class Outer
  {
    ...
    public class Inner
    {
    }
  }
}
...
public void ThisIsAnnoying()
{
  SomeNamespace.Outer.Inner silly = new SomeNamespace.Outer.Inner();
  ...
}

In this case, it is unclear that Outer is a class and not a namespace.  But what’s really annoying is the fact that even if you import  SomeNamespace into your class, you can only make your life so much easier because you cannot escape a class like you can a namespace:

namespace SomeNamespace
{
  public class Outer
  {
    ...
    public class Inner
    {
    }
  }
}
...

using SomeNamespace;

public void ThisIsAnnoying()
{
  Outer.Inner silly = new Outer.Inner();
  ...
}

You have now, as a designer, forced your users into at least partially-qualifying the path to the Inner class.  What is the benefit of this?  So long as Inner is being consumed outside of Outer, there is literally no benefit to having it nested inside another class.

There is one good time to use inner classes.  If you want to hide the implementation of a class or interface and only expose it by it’s abstraction, a nested inner class works well as part of a factory pattern:

namespace SomeNamespace
{
  public class Factory
  {
   
   public ISomeInterface Create()
   { 
      return new Inner();
   }
    ...
    private class Inner : ISomeInterface
    {
      ...
    }
  }
}
...

using SomeNamespace;

public void ThisIsAnnoying()
{
  Factory f = new Factory();
  ISomeInterface i = f.Create();
  ...
}

This is can be a very good design in the right circumstances.  The reason why is because you are forcing a decoupling between ISomeInterface’s design and it’s behavior.  You are, in fact, forcing clients not to care how the instance returned by Create works, because by making Inner private, it can only be constructed through the factory class.  It is only exposed through the abstraction, not it’s implementation.  This ensures that the behavior of Inner is contained within the Factory class and that nobody else needs to know – or can know – how it works.

But in all other cases, all you’re really doing is making developers’ lives more complicated by forcing them to spell.everything.out for no reason.