2008-07-10

Visual Studio #regions are a code smell

Why do #regions exists?

My best guess is that back in the the good old .NET 1.0 and 1.1 days, before partial classes, MS needed a way to visually remove, all the noise the auto generated Windows Forms code made. It kind a made sense, because you don't need to understand the auto generated code, you can just open the form in design view.

Why use #regions?

Often I see #regions used to group different code artifacts, like "Fields", "Constructors", "Properties", "Events", "Methods" etc. When the class gets big, navigating to an event handler becomes as easy as:

  1. Collapse all "regions.
  2. Expand the "Events" region
  3. Start to scroll for the event handler.

That is faster than scrolling through all the code in a big file.

Do we need #regions?

As with most other "coding tools", #regions tackle complexity. A class with several thousands lines of code, can be visually laid out in 20 lines or so. If you have a class with many, many lines of code, #regions do offer an advantage over normal layout. The #regions don't take up to much space compared to the total number of lines, so it is easy to ignore them if not needed. But if the #regions makes sense, they can be used to slice the lines into categories.

An obvious problem with #regions

Like any other categorization it falls apart if there are multiple dimensions. What if we are looking for an event handler, but the #regions define business rules?

My wife categorizes our pictures by month. She creates a folder with a "Month Year" name, and places pictures taken that month there. Every now and then we need to find a picture of someone, it could be my son. The problem with the "Month Year" categorization is that is does not help, we need a "who is on the picture" categorization.

If google created a fixed categorization, it would be much harder to find anything. Because the same topic could be categorized with many dimensions.

A not so obvious code smell lurking behind the #regions

So if #regions are good at categorizing many lines of code, why is it a code smell to use them?

This leads to another question.

>Why do we need to categorize?

The answer is easy.

>Because of the many lines of code.

And finally the question we should be asking

>Why do we allow many lines of code in a single file?

A single class with many lines of code, is called a god object. It is a well known anti-pattern, and will kill maintenance. I will not in depth with the god obejct anti-pattern, but it is well described elsewhere.

Moving away from the god class

Is it possible? It most certainly is...

CustomerDetailsForm

This form god'ified could look like this in code.

   1: using System;
   2: using System.Windows.Forms;
   3:  
   4: namespace GodClass
   5: {
   6:     public partial class CustomerDetails : Form
   7:     {
   8:         public CustomerDetails()
   9:         {
  10:             InitializeComponent();
  11:         }
  12:  
  13:         #region Events
  14:         private void CustomerDetails_Shown(object sender, EventArgs e)
  15:         {
  16:             DefaultFocus(_nameTextBox);
  17:         }
  18:  
  19:         private void _saveButton_Click(object sender, EventArgs e)
  20:         {
  21:             FocusAll(_nameTextBox, _name2TextBox, _addressTextBox, _address2TextBox, _phoneTextBox, _emailTextBox);
  22:             //Save the object
  23:         }
  24:  
  25:         private void _nameTextBox_TextChanged(object sender, EventArgs e)
  26:         {
  27:             TextBoxRequired(_nameTextBox);
  28:         }
  29:  
  30:         private void _name2TextBox_TextChanged(object sender, EventArgs e)
  31:         {
  32:             MoveTextToTextBoxIfTextIsEmpty(_nameTextBox, _name2TextBox);
  33:         }
  34:  
  35:         private void _addressTextBox_TextChanged(object sender, EventArgs e)
  36:         {
  37:             TextBoxRequired(_addressTextBox);
  38:         }
  39:  
  40:         private void _address2TextBox_TextChanged(object sender, EventArgs e)
  41:         {
  42:             MoveTextToTextBoxIfTextIsEmpty(_nameTextBox, _name2TextBox);
  43:         }
  44:  
  45:         private void _phoneTextBox_TextChanged(object sender, EventArgs e)
  46:         {
  47:             TextBoxRequired(_phoneTextBox);
  48:         }
  49:  
  50:         private void _emailTextBox_TextChanged(object sender, EventArgs e)
  51:         {
  52:             TextBoxRequired(_emailTextBox);
  53:         }
  54:  
  55:         #endregion
  56:  
  57:         #region Procedures
  58:         public void DefaultFocus(Control control)
  59:         {
  60:             control.Focus();
  61:         }
  62:  
  63:         public void TextBoxRequired(TextBox textBox)
  64:         {
  65:             if (string.IsNullOrEmpty(textBox.Text))
  66:             {
  67:                 textBox.Focus();
  68:             }
  69:         }
  70:  
  71:         public void FocusAll(params Control[] controlsToFocus)
  72:         {
  73:             foreach (Control controlToFocus in controlsToFocus)
  74:             {
  75:                 controlToFocus.Focus();
  76:             }
  77:         }
  78:  
  79:         public void MoveTextToTextBoxIfTextIsEmpty(TextBox firstTextBox, TextBox secondTextBox)
  80:         {
  81:             if (string.IsNullOrEmpty(firstTextBox.Text))
  82:             {
  83:                 firstTextBox.Text = secondTextBox.Text;
  84:                 secondTextBox.Text = "";
  85:             }
  86:         }
  87:         #endregion
  88:     }
  89: }

In addition, the tab order is set in the visual designer.

The problem with this sample is ofcourse, it is not several thousans of lines.

If we wanted to de-god'ify the class it could look like this.

   1: using System.Windows.Forms;
   2:  
   3: namespace NonGodClass
   4: {
   5:     public partial class CustomerDetails : Form
   6:     {
   7:         public CustomerDetails()
   8:         {
   9:             InitializeComponent();
  10:             new DefaultFocus(this, _nameTextBox);
  11:             new TextBoxRequiredMicroController(_nameTextBox);
  12:             new TextBoxRequiredMicroController(_addressTextBox);
  13:             new TextBoxRequiredMicroController(_emailTextBox);
  14:             new TextBoxRequiredMicroController(_phoneTextBox);
  15:             new ValidateFormMicroController(_saveButton, _nameTextBox, _name2TextBox, _addressTextBox, _address2TextBox,
  16:                                             _phoneTextBox, _emailTextBox);
  17:             new MoveTextToTextBoxIfTextIsEmptyMicroController(_nameTextBox, _name2TextBox);
  18:             new MoveTextToTextBoxIfTextIsEmptyMicroController(_addressTextBox, _address2TextBox);
  19:         }
  20:     }
  21: }

Things to notice, there are zero regions!

The microcontrollers look like this.

   1: using System.Windows.Forms;
   2:  
   3: namespace NonGodClass
   4: {
   5:     public class TextBoxRequiredMicroController
   6:     {
   7:         private readonly TextBox _textBox;
   8:  
   9:         public TextBoxRequiredMicroController(TextBox textBox)
  10:         {
  11:             _textBox = textBox;
  12:             _textBox.TextChanged += ((sender, e) => FocusIfEmpty());
  13:         }
  14:  
  15:         private void FocusIfEmpty()
  16:         {
  17:             if (string.IsNullOrEmpty(_textBox.Text))
  18:             {
  19:                 _textBox.Focus();
  20:             }
  21:         }
  22:     }
  23:  
  24:     public class ValidateFormMicroController
  25:     {
  26:         private readonly Button _button;
  27:         private readonly Control[] _controlsToFocus;
  28:  
  29:         public ValidateFormMicroController(Button button, params Control[] controlsToFocus)
  30:         {
  31:             _button = button;
  32:             _controlsToFocus = controlsToFocus;
  33:             _button.Click += ((sender, e) => FocusAll());
  34:         }
  35:  
  36:         private void FocusAll()
  37:         {
  38:             foreach (Control controlToFocus in _controlsToFocus)
  39:             {
  40:                 controlToFocus.Focus();
  41:             }
  42:         }
  43:     }
  44:  
  45:     public class DefaultFocus
  46:     {
  47:         private readonly Form _form;
  48:         private readonly Control _defaultControlToFocus;
  49:  
  50:         public DefaultFocus(Form form, Control defaultControlToFocus)
  51:         {
  52:             _form = form;
  53:             _defaultControlToFocus = defaultControlToFocus;
  54:             _form.Shown += ((sender, e) => FocusDefaultControl());
  55:         }
  56:  
  57:         public void FocusDefaultControl()
  58:         {
  59:             _defaultControlToFocus.Focus();
  60:         }
  61:     }
  62:  
  63:     public class MoveTextToTextBoxIfTextIsEmptyMicroController
  64:     {
  65:         private readonly TextBox _firstTextBox;
  66:         private readonly TextBox _secondTextBox;
  67:  
  68:         public MoveTextToTextBoxIfTextIsEmptyMicroController(TextBox firstTextBox, TextBox secondTextBox)
  69:         {
  70:             _firstTextBox = firstTextBox;
  71:             _secondTextBox = secondTextBox;
  72:             _secondTextBox.TextChanged += ((sender, e) => MoveText());
  73:         }
  74:  
  75:         private void MoveText()
  76:         {
  77:             if (string.IsNullOrEmpty(_firstTextBox.Text))
  78:             {
  79:                 _firstTextBox.Text = _secondTextBox.Text;
  80:                 _secondTextBox.Text = "";
  81:             }
  82:         }
  83:     }
  84: }

Even more these MicroControllers are reusable in the next form!

Things normally done(or forgotten) in the visual designer can also be micro controlled.
Tab order is as easy as.

   1: namespace NonGodClass
   2: {
   3:     public class TabOrderMicroController
   4:     {
   5:         public TabOrderMicroController(params Control[] controls)
   6:         {
   7:             for (int i = 0; i < controls.Length; i++)
   8:             {
   9:                 controls[i].TabIndex = i;
  10:             }
  11:         }
  12:     }
  13: }

Conclusion

If you use #regions, you might need to apply separation of concerns. This forces your code to be more readable, although it creates a navigation issue, when having lots of classes.

Creating an Active Directory Authentication Service

This should be as easy as a one liner, and guess what - it is :-)

Following the Dependency Inversion Principle, we define a high level policy class - well actually it is an interface.

public interface AuthenticationService
{
    bool Authenticate(string username, string password);
}

This hides the implementation detail from consumers.

Next we need to implement the actual ActiveDirectoryAutenticationService

using System.DirectoryServices.AccountManagement;

public class ActiveDirectoryAuthenticationService : AuthenticationService
{
    private readonly PrincipalContext _principalContext;

    public ActiveDirectoryAuthenticationService(PrincipalContext principalContext)
    {
        _principalContext = principalContext;
    }

    public bool Authenticate(string username, string password)
    {
        return _principalContext.ValidateCredentials(username, password, ContextOptions.Negotiate); 
    }
}

If you are using an IOC Container, like Windsor from the Castle Project, the configuration looks the this.
This should go in your main or global.asax, depending on the project type.

using System
using System.DirectoryServices.AccountManagement;

PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, Environment.UserDomainName)
IWindsorContainer container = new new WindsorContainer();
container.Register(
                    Component.For<PrincipalContext>().Instance(principalContext),
                    Component.For<AuthenticdationService>().ImplementedBy<ActiveDirectoryAuthenticationService>()
                  );

Now you are ready to use the AuthenticationService.

public class Consumer
{
    private readonly AuthenticationService _authenticationService;

    public Consumer(AuthenticationService authenticationService)
    {
        _authenticationService = authenticationService;
    }

    public void DoSomethingWhereAuthenticationIsNeeded(string username, string password)
    {
        if (!_authenticationService.Authenticate(username, password)) throw new SecurityException("Invalid username or password.");
    }
}

The end result is a code with low coupling, with an abstraction for a key business concern.

2008-07-09

Doing BDD, with Rhino Mocks AAA syntax

Ayende proposed a new AAA syntax in Rhino Mocks. I was wondering how it mixed with BDD.

Given this.

using System.Security;

public interface EmailService
{
    void Send(string message);
}

public interface AuthenticationService
{
    bool Authenticate(string username, string password);
}

public class SecureVault
{
    private readonly AuthenticationService _authenticationService;
    private readonly EmailService _emailService;
    private readonly string _secret;

    public SecureVault(AuthenticationService authenticationService, EmailService emailService, string secret)
    {
        _authenticationService = authenticationService;
        _emailService = emailService;
        _secret = secret;
    }

    public string GetSecret(string username, string password)
    {
        if(_authenticationService.Authenticate(username, password))
        {
            _emailService.Send(username + " successfully authenticated, and grabbed secret.");
            return _secret;
        }
        else
        {
            throw new SecurityException("Access denied!");
        }
    }
}

Using a stub test double, the if/else branch can be tested. This is called state based testing.

using System.Security;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using Rhino.Mocks;

namespace Specs_for_SecureVault
{
    [TestFixture]
    public class When_getting_secret_with_successful_authentication
    {
        private string _secret;
        private EmailService _emailService;

        [SetUp]
        public void Init()
        {
            var authenticationService = MockRepository.GenerateStub<AuthenticationService>();
            _emailService = MockRepository.GenerateMock<EmailService>();
            authenticationService.Stub(x => x.Authenticate("mortenlyhr", "pass1234")).Return(true);
            var secureVault = new SecureVault(authenticationService, emailService, "mysecretvalue");
            _secret = secureVault.GetSecret("mortenlyhr", "pass1234");
        }

        [Test]
        public void Should_return_secret()
        {
            Assert.That(_secret, Is.EqualTo("mysecretvalue"));
        }
    }

    [TestFixture]
    public class When_getting_secret_with_failed_authentication
    {
        [Test]
        [ExpectedException(typeof(SecurityException))]
        public void Should_throw_exception()
        {
            var authenticationService = MockRepository.GenerateStub<AuthenticationService>();
            var emailService = MockRepository.GenerateMock<EmailService>();
            authenticationService.Stub(x => x.Authenticate("mortenlyhr", "pass1234")).Return(false);
            var secureVault = new SecureVault(authenticationService, emailService, "mysecretvalue");
            secureVault.GetSecret("mortenlyhr", "pass1234");
        }
    }
}

So far so good, but what about interaction based testing?

The EmailService is a prime candidate for this. We can write an additional test for this expectation, in the "When_getting_secret_with_successful_authentication".

[Test]
public void Should_send_an_email_containing_the_username()
{
    _emailService.AssertWasCalled(x=>x.Send(Arg<string>.Matches(s=>s.Contains("mortenlyhr"))));
}

I don't think it can be any clearer that this, thank you BDD and Rhino Mocks ;-) - A match from heaven...

I am starting to see a pattern where mocks are private fields, and stubs have their return values as private fields. This is a lot less noise than when I did TDD, where every dependency was a private field. So again BDD helps you write less brittle specifications.

2008-07-08

Doing BDD, when expecting an exception

I really like the look of my tests specifications, they read almost like plain English.

After fumbling around for a while, I finally get how to specify an expected exception.

namespace Specs_for_Dictionary
{
    [TestFixture]
    public class When_adding_two_items_with_the_same_key
    {
        [Test]
        [ExpectedException(typeof(ArgumentException))]
        public void Should_throw_exception()
        {
            const string key = "UniqueKey";
            Dictionary dictionary = new Dictionary();
            dictionary.Add(key, new object());
            dictionary.Add(key, new object());
        }
    }
}

There is no Setup/Init method. Usually have one, that satisfies the "When_operation_on_state" class name. So that I can reuse the same specification context, for multiple expectations.

But then it hit me, that there can only be one "Should_expectation" method name, because the given "When_operation_on_state" always throws the exception.

2008-07-07

Doing BDD

What is BDD, go read JP's post Getting started with BDD style Context/Specification base naming

Basically it a shift towards specifying behavior instead of testing behavior.

The specification consists of 3 parts:

  1. A namespace with called "Specs_for_subject"
  2. One or more classes called "When_operation_on_state", with a SetUp/Init method that performs the "operation_on_state"
  3. One or more methods called "Should_expectation"

An example:

namespace Specs_for_Dictionary
{
    [TestFixture]
    public class When_adding_an_item_to_an_empty_dictionary
    {
        private Dictionary _dictionary;
        private const string key = "UniqueKey";
        private readonly object value = new object();

        [SetUp]
        public void Init()
        {
            _dictionary = new Dictionary();
            _dictionary.Add(key, value);
        }

        [Test]
        public void Should_contain_item_with_key()
        {
            Assert.That(_dictionary.ContainsKey(key));
        }

        [Test]
        public void Should_contain_item_with_value_for_key()
        {
            Assert.That(_dictionary[key], Is.EqualTo(value));
        }
    }
}

Since the "When_operation_on_state" part is the context, this where the meat is. In TDD I would usually have the test methods do the operation, and sometimes even setting the state. That often made me write brittle tests, that would stop working when making changes to non related code. BDD changed that for the better, not that it is impossible with TDD, but it is much easier with BDD.

An added side effect is the specifications read like plain English, so business rule specifications can actually be read be read by the customer.

2008-06-18

How to make a self extracting exe for xcopy deployment

Often I think MSI is overkill when all i need to do, is copy some files to a production server.

So how to set up TFS Build Server to Create a exe from a zip file. (Note I use the http://msbuildtasks.tigris.org/ to create the initial zip file).

I found the free http://www.disoriented.com/FreeExtractor/ , you need to download the optional command line version.

(Note I have a Tools folder at the root of my solution)

At the top of the TFSBuild.proj add the following:

<UsingTask TaskName="MSBuild.Community.Tasks.Zip" AssemblyFile="$(SolutionRoot)\Tools\MSBuildCommunityTasks\MSBuild.Community.Tasks.dll" /> 

Afterwards the folder can be zipped:

<CreateItem Include="$(DropLocation)\$(BuildNumber)\Release\**" >     <Output ItemName="ZipFiles" TaskParameter="Include"/>

  </CreateItem>

  <Zip ZipFileName="$(DropLocation)\$(BuildNumber)\deployment.zip" WorkingDirectory="$(DropLocation)\$(BuildNumber)" Files="@(ZipFiles)" /> 

And then use exec to call the MakeSFX:

<Exec Command="$(SolutionRoot)\Tools\FreeExtractor\MakeSFX.exe /nogui /zip=%22$(DropLocation)\$(BuildNumber)\deployment.zip%22 /sfx=%22$(DropLocation)\$(BuildNumber)\deployment.exe%22 /defaultpath=%22%24curdir%24%22 /exec=%22Deployment\AutoDeploy.bat%22 /autoextract /delete" IgnoreExitCode="true"  /> 

All you need to do is make make a bat file called AutoDeploy.bat, and do the xcopy operations from there.

2008-05-21

Using NUnit and NCover with TFS Build

Just in case you are using TFS as a Source Control and Build Server, does not exclude you from using NUnit and NCover.

First we need a MSBuild task for running NCover: NCoverExplorer.Extras-1.4.0.5.zip

Extract the "NCoverExplorer.MSBuildTasks.dll" file to the folder where the "TFSBuild.proj" is located. Add the file to TFS Source Control, and do a check-in.

Since the build server needs NUnit, NCover and NCoverExplorer they should be placed in a folder under source control like "Tools".

All that is left is to modify the modyfy the TFSBuild.proj file.

At the start.

  <!-- Do not edit this -->   <Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\TeamBuild\Microsoft.TeamFoundation.Build.targets" />
<!-- Start add the NCover MS Build Tasks -->     <UsingTask TaskName="NCoverExplorer.MSBuildTasks.NCoverExplorer" AssemblyFile="NCoverExplorer.MSBuildTasks.dll"/>     <UsingTask TaskName="NCoverExplorer.MSBuildTasks.NCover" AssemblyFile="NCoverExplorer.MSBuildTasks.dll"/>     <UsingTask TaskName="NCoverExplorer.MSBuildTasks.NUnitProject" AssemblyFile="NCoverExplorer.MSBuildTasks.dll"/>

<!-- End add the NCover MS Build Tasks -->     <ProjectExtensions>

And in the end

<Target Name="NCover">        <CreateProperty Value="%(ConfigurationToBuild.FlavorToBuild)">
            <Output PropertyName="FlavorToBuildValue" TaskParameter="Value" />        </CreateProperty>        <CreateItem Include="$(BinariesRoot)\**\*Tests.dll">            <Output TaskParameter="Include" ItemName="TestAssemblies" />        </CreateItem>        <NCover          ToolPath="$(BuildDirectory)\Sources\Tools\NCover\"          WorkingDirectory="$(BinariesRoot)\$(FlavorToBuildValue)"          CommandLineExe="$(BuildDirectory)\Sources\Tools\NUnit\nunit-console.exe"          CommandLineArgs="@(TestAssemblies) /xml=$(DropLocation)\$(BuildNumber)\NUnit.xml /labels /nologo"          CoverageFile="$(DropLocation)\$(BuildNumber)\release_test_results.xml"          LogFile="$(DropLocation)\$(BuildNumber)\coverage.log"      />    </Target>     <Target Name="CreateNCoverReport">         <NCoverExplorer           ToolPath="$(BuildDirectory)\Sources\Tools\NCoverExplorer\"           ProjectName="$(TeamProject)"           ReportType="ModuleClassFunctionSummary"           OutputDir="$(DropLocation)\$(BuildNumber)\"           XmlReportName="ncoverreport.xml"           HtmlReportName="ncoverreport.html"           ShowExcluded="False"           SatisfactoryCoverage="80"
          CoverageFiles="$(DropLocation)\$(BuildNumber)\release_test_results.xml"           Exclusions="Assembly=*Tests"   />     </Target>     <Target Name="AfterCompile" DependsOnTargets="NCover;CreateNCoverReport">         <Message Text="AfterCompile target executed."> </Message>     </Target>

In every build there should be a file called ncoverreport.html