Sunday, December 28, 2008

Effectively teaching test-first: Make it go green!

When you’re producing quality code using Test Driven Development you’re likely to use either the test first or test last approach (or more likely; a mix of those). Test first means that you write your test before you implement the method you’re testing (i.e. the functionality). If you’re following the test last mantra, you would implement the functionality first and then add test(s) to verify the behavior of the method. Strictly speaking, the latter approach will IMO not be a test driven development. If you want your tests to drive the architecture of your application, you should definitely go for the test first. It’s not that the test last won’t give you a testable application, it’s just that writing the test first makes it far easier to get your test actually be an unit test and not an integration test.

"I'm trying to free your mind, Neo. But I can only show you the door. You're the one that has to walk through it."

I must confess; I felt that writing tests first was really hard in the beginning. Before you start mastering the art of unit testing, you cannot really write the tests first unless you get some good guidance doing it. I’ve been doing TDD for a while now and I feel quite confident about it, and so I try to teach my team members the same philosophy. And the method I found that really helped getting them on the right track was to just sit down and do some pair-programming with them. We start out the session with me behind the keyboard. According to XP-ists the time between switching the roles of the driver (the one typing on the keyboard) and the observer (the one reviewing the code) should be around 30 minutes or so. But what I really find effective when it comes to teaching test first, is to do the switching after I’ve written the unit test. When writing the unit test itself, I do this while thinking out loud and discussing the code with my fellow dev. That way I practically show him/her how I think when I write the test and (s)he will have a good starting point for implementing the functionality. After I’ve finished writing the test, I just hand over the keyboard saying; “Make it go green!”

Would this method work in all circumstances? Certainly not! If (s)he was totally new to testing and I were to give an intro to unit testing, I’d probably choose another way. I’d probably show how to do some integration or unit testing on existing code before introducing the test first approach. Doing this exercise with someone who’s never seen a unit test before would probably be too much to grasp at once. When I’m coding the unit test in the Make-It-Go-Green-method I often have to use mocks to isolate the method under test and to introduce mocking to developers who have never seen unit test before will probably not be a good idea. In that case I’d rather let them do some integration tests before teaching them some real TDD. But maybe that’s just me…

Sunday, December 21, 2008

MemberAccessException

Exceptions are meant for those exceptional conditions that never should happened during your programs lifetime, but that you cannot guarantee won't happen. As you might expect from this statement, I'm not a big fan of sprinkling the code with unnecessary exception throws. I find it more useful to test those exceptional cases using unit and integration tests.

Anyway; while studying the source code from the excellent CodeProject article "NHibernate Best Practices with ASP.NET" by Billy McCafferty, I came across this quite interesting use of MemberAccessException;
public IOrderDao OrderDao
{
  get
  {
    if (orderDao == null) {
      throw new MemberAccessException("OrderDao has not yet been initialized");
    }
    return orderDao;
  }
  set { orderDao = value; }
}
If it were me coding this, I’d probably just throw the far more general ApplicationException or something (if I'd throw it all, mind my words in the intro to this post). But I definitely see that the MemberAccessException would be a lot better fit for this exceptional case.

Monday, December 8, 2008

Excellent blogposts on DDD and NHibernate

I'm in the process of setting up NHibernate on a new project and we've decided to try to let the domain model drive our development. Meaning; we're trying to follow the Domain Driven Design mindset. And as I'm quite new to both NHibernate and DDD, reading the 9-parts series called "A Journey with Domain Driven Design (and NHibernate)" by Ben Scheirman really gave me a good start. But unfortunately there's no summary post for his article series, so for my own reference I'll add it here;

Part 1: Intro and project structure: "In the first few articles, we will see how to start projects using NHibernate, go over some basic topics, and then get progressively more complex as we explore the many features of the ORM tool."

Part 2: Domain model: "This time I am going to start off creating a pet project to demonstrate how to implement these ideas. First we’ll implement a simple domain model to support our features. We will combine these with unit tests to verify behavior."

Part 3: Unit testing: "When testing, whether you practice test-driven development (TDD) or not, it is important that your tests and your code follow each other closely. (...) I’m not a TDD purist, but I try to write the tests first to let the consumer (the calling code) drive the design."

Part 4: Unit testing with transactions: "Let’s get on with the more interesting tests. Another thing I’d like to note is that, the tests here pass, but only after I write the appropriate code in the model to satisfy the test. I am purposefully omitting the domain model code at this time because it is unimportant. You should be able to understand what the code does without looking inside the class. "

Part 5: Database schema and NHibernate config/initialization (ISessionFactory, ISession): "Let’s create a database structure to support persistence of our domain model."

Part 6: NHibernate mapping: "We’ll dive in deeper with NHibernate and mapping in this article."

Part 7: NHibernate mapping with associations/relations: "We introduced some simple mapping concepts, and this time we’ll dig in a bit deeper."

Part 8: NHibernate split mapping files, building a Repository and saving to the database: "We left off last time with our first association mapped and tested. Let’s dig in a bit deeper with NHibernate mapping.(...) Repository takes advantage of generics to avoid a lot of duplicate code. This is a quick implementation of the Repository pattern (...)"

Part 9: Higher level tests: "In this article, part 9 of the series, we’re going to wrap up our initial feature list and focus on building a user-interface for our video store, named Videocracy."

Sunday, November 16, 2008

Empty delegate makes event raising easy and thread-safe

I'm currently working on a project that will use some of the guidelines from the WPF Composite Application Guidance. And as I was studying the source code I kept seeing a strange
initialization of events that looked something like this;
public event EventHandler EmptyDelegateEvent = delegate { };
I mean; I do know my way around delegates, but these empty delegates puzzled me. After googling around a bit I found that this was a just a clever way of avoiding null reference exception when raising the event. So instead of this;
public event EventHandler CheckForNullEvent;

void RaiseEvent()
{
  // the usuall way
  if (CheckForNullEvent != null)
    CheckForNullEvent(this, new EventArgs());
}
...you can simply do this;
public event EventHandler EmptyDelegateEvent = delegate { };

void RaiseEvent()
{
   // the easy way
   EmptyDelegateEvent(this, new EventArgs());
}
When using empty delegates you can simply raise the event without checking for null. Note though, that performance wise it will be better to do the "if not null" check than a "delegate {}". But I ran some performance testing to compare the two, and the performance hit is really not that big of an issue. Even though the performance of the empty delegate was 20-30% slower than the null check, the time it takes to do either of them is miniscule. This is really not where you should put your performance tuning effort. A 'null reference exception', which is much more likely to happen if you forget to check for the null, will have a much bigger impact on the overall performance of your application. Or even worse; if a raise condition occurs. Which again reminds me that the correct way of checking the event for null and at the same time making sure it's thread-safe, is this;
void RaiseEvent()
{
   // the thread-safe way
   EventHandler copyOfEvent = CheckForNullEvent;
   if (copyOfEvent != null)
       copyOfEvent(this, new EventArgs());
}
And how many does actually do that? And talking of performance; what about 'developer performance'? Instantiating an empty delegate and no need for null checking or possible raise conditions, means faster coding and less bugs - e.g. better developer performance.

Kjetil.Klaussen.ToString()

Hi, and welcome to my blog!

I’m a .NET developer working for the Trondheim-based company Sentinel Software, where we're building the next generation sales-support tool for car dealers.

I started out in this geekie world as a database/web developer on Microsoft SQL Server 2000 and classic ASP. And even though I still enjoy programming intricate joins in T-SQL, since I was introduced to .NET and C# in 2001 I have never missed classic ASP.

In my early days as a .NET-developer I mainly worked on ASP.NET WebForms. Later I moved over on the desktop and starting building WinForms, but still with some ASP.NET work occasionally. Since late 2007 I've been fortunate enough to work on WPF and I must say that I'm immensely pleased with this framework and hopefully I’m all done with WinForms.   

Strongly influenced by my former colleague Pål Fossmo I’ve also developed a strong feeling for Test Driven Development. What I really enjoy about TDD is the confidence that testing gives me. It makes me sleep better at night knowing that the code I wrote today has been proven to work and I didn’t mess up any other parts of the application writing it.

Closely related to the awakening experience of testable code is my interest in design patterns and beautiful code. These three pillars – testable, pattern based, well-written code – are what I consider the very core of developing good, maintainable software. I believe that one of my main responsibilities as a developer is to make whatever code I write understandable and thereby maintainable to the guy or gal next to me. Because when I move on to the next project/job, (s)he is the one who’s going to maintain and build on to the code I just left behind. Taking pride in making that an as easy job as possible is always my number one priority.

I was awarded an Microsoft MVP in C# in July 2014.