Friday, 2 April 2010

xUnit.net vs MSpec?

For my personal projects I use MSpec as a testing framwork. MSpec had it's advantages and disadvantages. Here is an example of a test I wrote.
   37 public class When_setting_the_state_of_a_host
   38 {
   39     private static HostCheckResultCommand command;
   40     private static HostCheckResultCommandHandler commandHandler;
   41     private static IRepository _repository;
   42     private static Host _host;
   43 
   44     Establish context = () =>
   45     {
   46         _host = new Host("asterix");
   47         _repository = MockRepository.GenerateMock<IRepository>();
   48         _repository.Expect(x => x.GetById<Host>(""))
   49                    .IgnoreArguments()
   50                    .Return(_host);
   51         _repository.Expect(x => x.Add<Host>(null)).IgnoreArguments();
   52         command = new HostCheckResultCommand("asterix", HostState.Up);
   53         commandHandler = new HostCheckResultCommandHandler(_repository);
   54     };
   55 
   56     Because of = () => commandHandler.Execute(command);
   57     It should_have_a_HostStateChanged_event = () => ((IEventProvider)_host).GetChanges().First().ShouldBeOfType<HostStateChanged>();
   58     It the_event_should_have_HostState_Up = () => ((IEventProvider)_host).GetChanges().First<HostStateChanged>().NewState.ShouldEqual(HostState.Up);
   59 }
MSpec has a lot of advantages:
  • Once you are used to lambda expresions, it is relative easy to read.
  • Since every test is in it's own class, tests can't conflict with each other.
  • Every test statement (It) is named and run even when another test statement failes.
Disadvantages:
  • Everything in the class should be static, since the use of anonymous functions.
  • Can be difficult to get started.
At work I started using xUnit.net as testing framework.
    1 public class A_Person : XPODatabaseTestFixture
    2 {
    3     [Fact]
    4     public void can_be_created()
    5     {
    6         Person person = ObjectSpace.CreateObject<Person>();
    7         Assert.NotNull(person);
    8     }
    9 }
Well we don't compare the tests, because they are completly different, but we can compare the frameworks.
The main advantages xUnit.Net has are:
  • Every test is performed isolated, for every test method a new instance of the object is created.
  • The test runner is very fast, tests are run in different threads, multiple at a time.
  • Can use the constructor for common setup and IDisposable for teardown. (Setup and teardown contain logic that is run before and after each test. other frameworks use the [Setup] and [Teardown] attributes)
The only disadvantage I found in both (and other) test framework is that there is no VisualStudio testsrunner provided. You either need to use the extenal test runner they provide, or a tool like Testdriven.Net, Resharper or DevExpress Coderush.

Although I like MSpec very much, I am going to dump it for xUnit.net. With xUnit.net I don't have to think about making my members static.

Friday, 19 February 2010

CQRS the simple way.

CQRS stands for Command Query Responsibility Segregation and is a pattern that splits an application into two parts: Commands and Queries.
Queries are used to get data from a datasource (like a database) and commands are used to do something with the data.
The simplest form of CQRS is the following:


public interface BlogQueryService
{
    IEnumerable<Blog> GetAllBlogPosts();
    Blog GetBlogPost(int blogid);
    IEnumerable<Comment> GetAllCommentsForPost(int blogid);
}

public interface BlogCommandService
{
    void NewBlogPost(string title, string text);
    void EditBlogPost(Blog editedBlog);
    void AddComment(int blogid, string comment);
}

The BlogCommandService just updates the datasource with the given data (and does validation if needed) the query service just return simple data.
Of course this is not scalable and a lot of advantages that Udi Dahan and Greg Young describe are not here, but it is a first step to decouple a lot of applications.

Monday, 15 February 2010

Make development easier and faster with unit testing


As software developers we always come across bugs, some bugs are not very difficult to fix and other bugs are more difficult. Sometimes it is even hard to find the place in code where the bug is coming from and sometimes when we fix a bug we introduce several other without knowing it.
The solution for this problem are unit tests.

Another problem we have is that the user wants to know that the software (s)he is using is reliable. We as software developers should be able to tell the user that the software we are writing is reliable. And we should be able to tell that we have implemented features the way the user wants it and not the way we think they want it or should use it. Basically the user is king.
The way to get some reliability is unit testing.

So what are unit tests?
A unit test is code that is testing the software we have been writing or are going to write. You can test software on multiple levels.
First we can test functions/methods directly like this:
public int Add(int x, int y)
{
    return x + y;
}

[Test]
public void TestAdd()
{
   int result = Add(2, 3);
   Assert.AreEqual(5, result);
}
Second you can test bigger parts of the system:
   1:  [Test]
   2:  public void When_playing_files_that_donot_exist_give_error()
   3:  {
   4:      ProgramPlayer player = new ProgramPlayer();
   5:      try
   6:      {
   7:         player.Play("filethatdoesnotexist.mp3");
   8:         Assert.Fail("Exception was not thrown");
   9:      }
  10:      catch(FileNotFoundException ex)
  11:      {
  12:          Assert.IsNotNull(ex);
  13:      }    
  14:  }
And you can test complete usecases and programs.

For most people it seems like wast of time to write unit tests. When I first started with unit tests it was like I wasted time (although at that time I was at university), but after some time and a lot of improvements I realized that unit testing does help. Last year I had to write code for some really difficult calculation. A colleague made the calculations on paper so that I could validate it.
So I wrote some tests for all those calculations and I started to work out a solution.
I soon found out that is was easy to split up the solution in multiple parts, so I wrote unit tests for each part of the solution as well and soon I had a working implementation.
At that moment I didn't even have a user interface to test it in. I found out that working with unit testing is much faster than without. You can test specific parts of the program very fast without the need of starting the application and navigate to the place where you are using the feature you are testing.

Thursday, 7 January 2010

Refactor spagethi Form code to something usefull

There are a lot of applications that are very difficult to maintain. The original writers would not always agree about that statement, but others will see their code as an unmanageable mess.
I will not blame the original writers of those applications. A lot of them started with software development as their hobby or out of interest. During time they learned some "best practises" by reading tutorials about how to write desktop applications using forms (like in Visual Basic or Delphi). These tutorials tell you that in the event handlers you put the code that should be run when somebody presses a button or when an item is selected. There are even components like timers that could let you do stuff at specific times / intervals.
For tutorials this is OK and I did it as well, but I realised that it is plain stupid to do so. The problem is that you get large chunks of code within event handlers and forms. At some point it will be difficult to know where some piece of code can be found. Is it on FormA, FormB or (even worse) on both?

In the rest of this post I want to describe some small steps to re-factor to easier to maintain and understand code. As an example I use a simple application to manage data from media files. There is a form that add/edit music, it has a save button and  a close button.

Get code out of event handlers.

The first step is to get event handlers as small as possible. Put all the code that is currently in the event handler into a method and call that method in the event handler. An example:
In the form for adding and editing music information we have a lot of code in the OnSaveClicked event handler. There is code to see whether we are adding or editing the music, there is code to fill the data set (or the sql query, or whatever we are using for persistence) and there is some validation code. That would be at least 15 to 30 rows of code. (depending on how much information we can fill in). By moving all this code to a separate method we can easily call this same method from the OnClosed event handler to let the user save the changes when closing the form.

Split code that is interacting with the controls from other code.

In the method to save the music information we are still asking the information from every input control. So let say we have a textbox to fill in the year of when the music is written, we would call txtYear.Text to get the information. We will probably do this at least two times (one for the validation, because this is a required field and two for saving the value). When we want to change to control to a DateTime control, we have change the code for validation and the code for saving the value which could lead to unexpected behaviour (a.k.a. bugs).
A better way would be to have a method that accepts parameters (one for every field that should be saved). You will then get the following code:
public void OnSavedEvent(object sender, EventArg e)
{
    SaveMusic();
}

private void SaveMusic()
{
    string name = txtName.Text;
    // int year = Int32.ParseToInt(txtYear.Text); // we used a textbox but now we have a special control called YearPicker which gives back an integer.
    int year = yearPicker.Year;
    string composer = txtComposer.Text;

    SaveMusic(name, year, composer);
}

private void SaveMusic(string name, int year, string composer)
{
    // do a lot of stuff with name, year and composer
}
This way we can easily change a control without worrying about whether something goes wrong with saving the data.

Separate concerns.

To be honest, I don't like to much knowledge within a form. A form is there to display data and to handle input and  a little but for orchestrate the application flow (more on this in a later post).
Doing stuff with data (and getting the data) could better be done in a separate class. So we can create a class called MusicDataService, which has the SaveMusic(string name, int year, string composer) method. It will also get some methods to load the data.
public struct Music
{
    public string Name;
    public int Year;
    public string Composer;
}

public class MusicDataService
{
    public void SaveMusic(Music music) {/* lot of stuff to be done... */ }
    public Music GetMusicWithName(string name) {/* lot of stuff to be done... */ }
}

public class MusicAddView()
{
    private MusicDataService _service = new MusicDataService();
    public void OnSavedEvent(object sender, EventArg e)
    {
        SaveMusic();
    }
    
    private void SaveMusic()
    {
        Music music = new Music();
        music.name = txtName.Text;
        music.year = yearPicker.Year;
        music.composer = txtComposer.Text;
    
        _service.SaveMusic(music);
    }
}
Now that we have the knowledge of saving music separated from it's form, we can use the same code at multiple places if we want.

Smaller methods.

As I said the SaveMusic method in the MusicDataService contains a lot of logic. It validates the input and it makes sure that it gets persisted. Since validation on it's own can contain a lot of code, it is recommended to put this in a separate method as well. This gives us an other advantage. We can now validate the Music structure multiple times even when we don't want to save. When editing the object we can directly validate the input and gave the user feedback.
The real implementations of validating and saving data I will not show, since this is very specific for each applications and there are just to much ways of doing it (and frameworks that could be used). This said it is probably a good idea to make that code pluggable, so we can swap the implementation if we want to. (how to do this could be another post.. you can also use google)

Conclusion.

In this post I tried to show that using some easy steps it is not to difficult to make your program easier to maintain, easier to test and easier to understand for new software developers. And this all leads to a more solid application.