Tuesday, February 28, 2012

Small unit testing tip

When asserting the content of collections, lists, dictionaries,... in unit tests, don't do this:

Assert.That(this.result.Contains(this.expectedResult1));
Assert.That(this.result.Contains(this.expectedResult2));

Or this:

Assert.AreEqual(this.expectedResult1, this.result[0]);
Assert.AreEqual(this.expectedResult2, this.result[1]);

What if you implemented your method wrong, and the result contains more than two elements? Unless you're totally not interested in the size of the result, always check if the collection is as big as you expect it to be:

Assert.AreEqual(2, this.expectedResult.Count);
Assert.AreEqual(this.expectedResult1, this.result[0]);
Assert.AreEqual(this.expectedResult2, this.result[1]);

Sunday, February 26, 2012

Speed up development with snippets

Do you find yourself often writing the same pieces of code? I guess we all do: the INotifyPropertyChanged interface and the PropertyChanged method in WPF projects are one example. Unit tests more often than not have the same structure (at least on a per-project basis).

Visual Studio's snippets functionality can speed up your work in this regard. I knew about snippets since some time, but never actually used them. I recently noticed I had to type the same code for unit tests over and over again, and decided to check out how snippets could help. I encourage you to do the same.

First, see the structure in your code. I like unit tests that look like:

[TestFixture]
p
ublic class WhenAddingElementToCollection() : UnitTestBaseClass
{
     private MyCollection _collection;
     private Element _element;
     public override Given()
     {
          _collection = new MyCollection();
     }

     public override When()
     {
          _collection.Add(_element);
     }

     [Test]
     public void ShouldIncrementCount()
     {
          Assert.AreEqual(1, _collection.Count);
     }
}

The class inherits from a UnitTestBaseClass that provides the structure to make all unit tests alike. You can easily make a snippet for this. Let's make a snippet for the Given() and When() overrides:

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="
http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>GivenWhen overrides</Title>
      <Description>Provides two method overrides (Given and When) for unit testing in Cassis.</Description>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
      <Shortcut>gw</Shortcut>
    </Header>
    <Snippet>
      <Code Language="CSharp">
        <![CDATA[/// <summary>
  /// Initializes the context in which the test should run
  /// </summary>
  protected override void Given()
  {
   base.Given();
  }

  /// <summary>
  /// Does something in the system that will be asserted later on
  /// </summary>
  protected override void When()
  {
   base.When();
  }]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Save this as a .snippet file (I saved it in my Visual Studio 2010\Code Snippets\Visual C#\My Code Snippets folder) and it should be available. You will also see it in your Code Snippets Manager (available under the Tools menu in Visual Studio). The XML should be fairly straight-forward. Now, typing in 'gw' and pressing tab twice will generate the snippet. Then, you can tab through the different fields.

I made a different snippet for the should method:

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="
http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Should method</Title>
      <Description>Provides a Should... method for unit testing in Cassis</Description>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
      <Shortcut>should</Shortcut>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>method</ID>
          <ToolTip>What to assert.</ToolTip>
          <Default>HaveDoneSomething</Default>
        </Literal>
        <Literal>
          <ID>summary</ID>
          <ToolTip>Summary of what this method is asserting.</ToolTip>
          <Default>something was done</Default>
        </Literal>
        <Literal>
          <ID>implementation</ID>
          <ToolTip>Implementation of the method.</ToolTip>
          <Default>Assert.</Default>
        </Literal>
      </Declarations>
      <Code Language="CSharp">
        <![CDATA[/// <summary>
  /// Asserts that $summary$.
  /// </summary>
  [TestMethod]
    public void Should$method$()
  {
   $implementation$
  }]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

At first, this takes some discipline to actually use the snippets. But once you get used to it, it really speeds up your work.

If you have ReSharper, these snippets will work, but you won't see them in Intellisense, because ReSharper overrides your Visual Studio Intellisense. ReSharper offers Live Templates that do the same and more. That might be for another post, but they're easier than Visual Studio's snippets, and have more possibilities.

Wednesday, January 18, 2012

How to use NHibernate's SQLCriterion - take 2

After having an interesting discussion with Stefaan (colleague, friend, ex-colleague and now colleague again) about my previous post on NHibernate's SQLCriterion, I decided to have another look at my usage of SQLCriterion.

He argued that with SQLCriterion, you're more or less working around the ORM, which I can agree with. After putting it on StackOverflow, I got three answers and tried all three.

This is what I went with in the end:

ISessionFactory sessionFactory = GetSessionFactory(); 
ISession session = sessionFactory.GetCurrentSession(); 
ICriteria criteria = session.CreateCriteria(); 
return session.QueryOver().Where(c => c.Group.Id == groupId).List(); 

A more elegant solution.

Sunday, January 8, 2012

How to use NHibernate's SQLCriterion

I recently needed to use NHibernate's SQLCriterion, but lost some time on finding out how to use it. Once you've found it, it's quite simple actually:


ISessionFactory sessionFactory = GetSessionFactory();
ISession session = sessionFactory.GetCurrentSession();
ICriteria criteria = session.CreateCriteria<Customer>();

var sqlString = new SqlString("{alias}.GroupId = " + groupId);
criteria.Add(new SQLCriterion(sqlString, new object[0], new IType[0]));

return criteria.List<Customer>();

The {alias} is there so NHibernate knows where to put the table name. I'm not so sure about the second and third argument of the SQLCriterion constructor, but in my case, I didn't need them. Just don't pass in null or you'll get an exception.

If you need a more advanced SQLCriterion, check out this post by Remco Ros.

Friday, October 7, 2011

Trunk based development

In our team, we’ve recently changed our source control strategy to what’s now being called ‘trunk based development’. This has reduced the amount of merge-headaches we were having.

In the past, we used a form of branch-per-feature with only one branch. We would have a trunk and a development branch (we’re using Subversion). Coding would be done on the development branch, and when a story/feature was finished, it would be merged to the trunk. After the merge, a new development branch was made. The trunk was, in effect, always releaseable.

At least, that was the theory. This didn’t really work in practice:

  • sometimes a feature can’t really be released without the next story
  • bits and pieces of the next story would have been implemented before the previous story had been finished (otherwise developers would be sitting around, waiting for the merge before committing)

More importantly, this slowed us down because:

  • there were conflicts when merging (when a fixes branch touching the same code had been merged in the trunk)
  • it takes some time to merge, build, commit, delete the old branch and make a new branch (meanwhile, teammembers can’t commit code to the old branch)
  • this is inherently error-prone, as conflicts could be resolved wrongly, (re-)introducing bugs, often only discovered when the code was already in production

Finally, there was no need for our trunk to always be releasable, because we know when we’re going to release and with any modern source control system, you can jump back to certain revisions.

Curing headaches

Switching to trunk-based development is easy and we haven’t looked back since. The point is:

  • Develop and commit to the trunk
  • Make tags from the trunk
  • Bugfix branches are made from the tag, but are merged to the trunk again of course

The only problem you can have, is at that moment just before a release. There are two smaller tasks that need to be finished for the tag, but other developers want to start with the next story. This next story is not allowed to be included in the tag.

The solution is simple: make a branch to finish the work for the tag. Finish the job, make the tag from this branch en merge the changes back into the trunk. No need to remove this branch as it can serve as a bugfix branch.

Here’s a colorful diagram to make this post look professional:

Trunk based development

In the end, this makes our development track more fluent, less stressful, less complicated, and hasn’t given us any problems.

At the moment we researched this, there wasn’t very many information to be found. But these are the articles we based our decision on:

Wednesday, August 24, 2011

Coding pet peeves

This was a blog post I had lying around, waiting to be posted. This post on code smells on the All Your Base Are Belong To Us blog reminded me of it. So here goes.

Everyone has coding pet peeves. Pieces of code they can’t resist the urge to change when they see it. Of course, there will be exceptions, or cases where it’s impossible to change the code, or just not worth it. But not that often. Apart from wrapping all your methods in try-catch blocks, here are two other of my coding pet peeves.

Helper classes

Helper classes are classes whose names end in 'Helper’. In my line of work (hospitals): PatientHelper, AnamnesisHelper, etc. Sometimes they might end in ‘Utilities’. They all have several things in common, starting the the too general name.

The Single-Responsibility-Principle requires that a class has one responsibility. This, to me, implies that it shoud have a clear and unambiguous name. Helper or Utilities is not clear.

The biggest danger with classnames like this, is that these classes can become too big, with all sorts of methods dumped in them.

There are several ways you can get rid of these classes. Remove them method by method. I’ve been able to move methods to repositories, domain objects, controllers, extension methods, etc. All classes that are loud and clear in what they do (extension methods are a bit special).

One file per class

Why would you put multiple classes in one file? Usually, it’s because it’s a small class, an enum probably. The advantage is laziness, I believe. The advantage of one class-one file, is that you can easily see all classes in your IDE of choice. Which is a small advantage, maybe. But it is a pet peeve, so it doesn’t always have to be fully rational, no?

Also, files are cheap, so no need to ration them.

A bigger advantage becomes apparent when you’re using source control. When opening the log file, you can more easily search for changes to a class, because a class and a file are the same. You don’t have to inspect the diff to know if your class changed, or it was just something added to the enum.

Pet Peeves

I guess everyone has their personal style of coding, and their personal coding pet peeves. What are yours? What small things make you cringe when looking at code?

Saturday, June 25, 2011

Exceptions everywhere

On two projects I have worked on, I’ve seen a lot of this:
public void DoSomething()
{
try
{
// actually do something here
}
catch (Exception ex)
{
throw new Exception("Unable to do something", ex);
}
}


I’ve seen this in various differing styles:
  • not including the original exception in the newly thrown one (ouch!)
  • having a custom Exception type, indicating where in the code/assemblies the exception happened.
Reasons seem to be a desire to easily see where the exception occurred. So a DomainException would indicate the exception happened in the Domain DLL. Another reason was to easily see the methods called. In the log of an exception, you can then see all the “sub-exceptions”.

Of course, this can all be seen in the stacktrace, and I believe it has its origins in the old days of coding, where you would have to set up your exception handling manually. But in .NET, this all happens automatically, and you’ve got a full stacktrace to help you find the problem.

Even more, wrapping each method in a try-catch construction gives for more code-noise when you’re scanning a class. More for your brains to process, harder to find what you’re looking for, etc.

So: no advantages, only disadvantages. Only catch an exception if you’ll do something with/about it. Log it, swallow it, mention it to the user. But if you’re only going to rethrow it, don’t. Just don’t. Catch your exceptions at the top-most level.

Oh, and never do this:

if (myObject == null)
{
throw new Excpetion("myObject is null");
}

Yes, I’ve seen this. It’s no shame if you’ve ever coded this, but remove it when you see it.