RSS
Facebook
Twitter

Monday, February 21, 2011

Spot the bug – misbehaving server

We had a strange issue at work – we had a misbehaving server, who worked perfectly well with one client but had strange issues when several clients connected to it. The server would broadcast a message to all of its clients but only one client would receive that specific message, re-sending the message would fix the problem occasionally but it wasn’t a very consistent behavior.

I’ve managed to find the root of the issue and created a simplified version of the issue. can you spot the bug in the following code?
public class Server
{
    public void SendPingToClients(IEnumerable<client> clients)
    {
        foreach (var client in clients)
        {
            Task.Factory.StartNew(() => Ping(client));
        }
    }

    public void Ping(Client client)
    {
        Console.WriteLine("ping sent to client " + client.Id);
    }
}

Happy coding!

Wednesday, February 16, 2011

Multiple asserts – done right

If you’ve been writing unit tests for some time or seen a good presentation on how to write unit tests you probably heard the “One assert per test” rule. There are real benefits in having only one assert in each tests – you get a focused tests, it’s easier to understand what caused the test to fail as so on.

However there are several reasons to use more than one assert in a test – not only when you want to check several properties of the same result.

The problem is that it doesn’t matter whether or not it’s ok to write several asserts in one test when a test fails you’ll be stuck with a partial view – and that’s due to the assertion implementation – it throws exception on failure, and so the first assert that fails throws an exception leaving you completely oblivious to the result of the asserts following it (please excuse the overly simplified example):

[TestMethod]
public void SimpleTest() 
{
    var result = 2 + 2;

    Assert.IsInstanceOfType(result, typeof(double));
    Assert.AreEqual(4, result);
}

And so if the first assert fails I have no clue what is the state of the 2nd assertion.

The solution

I came across this idea while reading Multiple mocks, asserts, and hidden results:

If test frameworks did NOT throw exceptions form asserts\mocks, but instead gathered all of their data before ending the test as fail\pass, this would not be needed.

Obviously this feature is not yet supported and so a solution is up to us. Roy links to a tool that uses code generation to create different tests for each assert – how cool is that! But I thought that there bound to be a simple way to run multiple asserts and only output the fail results at the end of the test run – and there is:

public class AssertAll
{
    public static void Execute(params Action[] assertionsToRun) 
    {
        var errorMessages = new List();
        foreach (var action in assertionsToRun) 
        {
            try 
            {
                action.Invoke();
            }
            catch (Exception exc)
            {
                errorMessages.Add(exc);
            }
        }

        if(errorMessages.Any()) 
        {
            var separator = string.Format("{0}{0}", Environment.NewLine);
            string errorMessageString = string.Join(separator, errorMessages);
            
            Assert.Fail(string.Format("The following condtions failed:{0}{1}",
                         Environment.NewLine, errorMessageString));
        }
    }
}

And now our test looks like this:

[TestMethod]
public void SimpleTest2() 
{
    var result = 2 + 2;

    AssertAll.Execute(
        () => Assert.IsInstanceOfType(result, typeof(double)),
        () => Assert.AreEqual(4, result));
}

It’s not pretty but it works, and you get an error message for all the asserts that failed.

Conclusion

As always remember that “just because you can – doesn’t mean you should”, there are instances where multiple asserts in a single tests means that you’re testing too much in the same test – and it’s up to you to decide if it’s a good idea.


Related links:

When to use the SetUp attribute

Checking expected exception message when using MS Test

#Nose – the unit test discovery tool

Tuesday, February 15, 2011

Kanban workshop for leader/managers–Part II

a week ago (give or take a day) I attended a Kanban workshop by Agile consultant company, AgileSparks– the following is my impressions from that day along with my thoughts on the subject:

In the 2nd part of the day we continued the workshop at full speed – the next few hours were devoted to non-stop learning, it was a tiring but very educational experience - it’s amazing how much you can learn with only one 10 minute break.

Yuval Yeret, who presented the course, started by explaining the difference between Kanban and kanban (notice the k’) and the difference between change by Revolution to change by Evolution. I think Wikipedia has summarized it perfectly:

Kanban - A visual process management system that tells what to produce, when to produce it, and how much to produce.

The Kanban Method – an approach to incremental, evolutionary process change for organizations.

At this point we had a discussion within the group on how to create change and exchanged war stories about change in our place of work. This is the place where the workshop shines – I got to learn about how different companies have changed the way they work – it gave me quite a few ideas on how it can be done in my current job.

From there we’ve continued learning on how to create incremental change according to rules formulated by David J. Anderson:

  • Visualize the workflow
  • Limit Work In Progress
  • Measure and optimize flow
  • Explicit policies
  • Improve Collaboratively

The next topics were less about Kanban and more about tools to manage Agile process – TOC (Theory of Constraints), dealing with bottlenecks, the Five Whys to name a few. We’ve gone over several tools for operations review which I found interesting although not directly related to my day to day job. We went over a few real examples of companies that use Kanban and the methods and tools they’ve been using and finally ended up with a brief overview of Kanban vs. Scrum as well as Kanban and Scrum (a.k.a Scrum-ban).

It was a long and enjoyable day and I learnt a lot – it is yet to be seen how I’m going to use this newly acquired knowledge.

Epilogue

The following morning I marched into my boss office and enthusiastically explained to him about Kanban, WIP and how we can change the way we work. My boss listened patiently and after I finished explained why he believes that Scrum is a better fit to the way the team works right now, as it seemed that project managers would benefit more from the ability to find bottlenecks between the teams while right now at the development team we know perfectly well where the bottlenecks are.

So I did the only logical thing I could do – I went to the project’s manager and explained (briefly this time) about Kanban and its benefits – I made the first step and now I’m waiting to see what would happen…

 

Related links:

AgileSparks

Yuval Yeret’s blog

Wednesday, February 09, 2011

Kanban workshop for Leaders/Managers

Yesterday I had the opportunity to participate in a one day Kanban workshop by AgileSparks.P1050810

The workshop was intended for leaders and managers and so one morning I found myself sitting in a conference room with project managers, team leaders and one VP. Although it meant that not everything I learned was directly related to my day to day job I learnt quite a lot on how other parts of the organization view the development team – it was an eye opening experience.

The workshop was conducted by Yuval Yeret in a very agile way – in the beginning he asked us to write on sticky notes what we want to accomplish (yellow) and our questions regarding Kanban (purple). These notes joined other notes that Yuval has prepared each containing one of the subjects learned in the workshop in the course task board that had columns for to-do, learning, practice and done. I guess that a task board for a course was not enough because he also tracked the course progress using a burn chart – and it worked we were able to ask questions, have discussions and side step and the course changed according to what we wanted to learn about.

We’ve started by defining what is “agile” – which meant different things for different people, Some preferred to name practices such as TDD, SCRUM, daily meetings while other teams defined agile by its principles i.e. embrace change, get feedback from the product owner and so on.P1050816

After a short presentation about Kanban and a simple exercise to make sure we understood the basics we’ve played a game – each team was a company that used Kanban (obviously) to manage their tasks. After playing this game we had a good idea how to practice Kanban and what we should do in our organization – which was a good thing because it was time to go out to lunch

To be continued…

 

Related links:

AgileSparks

Yuval Yeret’s blog

Monday, February 07, 2011

How to ignore thrown exceptions

Yesterday I came across this question on StackOverflow:
Is there a better way to ignore an exception in C# than putting it up in a try catch block and doing nothing in catch? I find this syntax to be cumbersome. For a code block, can't I simply "tag" it in such a way so as runtime knows which exceptions to neglect?
This question was first answered that ignoring exception automatically couldn’t and shouldn’t be done. Some of the answers stated that you should never even think about “automatically” catching exceptions because there is a reason they were thrown in the first place -  I don’t agree. There are instances when you want to silently ignore exception raised (log if necessary) them and continue executing your code (DTE I’m talking to you).
So if you have a valid reason for ignoring exceptions there are two ways to solve this problem one is using a n higher order function method and the other is PostSharp.

Solution #1 - Higher order function

“Higher order function” is a term related to functions that receive another function as an argument and/or return a function. By passing a function as argument you can add a simple try-catch block around it then execute it.
public void IgnoreExceptions(Action act)
{
    try
    {
        act.Invoke();
    }
    catch { }
}

And then the following line will ignore all exception thrown from Foo:

IgnoreExceptions(() => foo());

I prefer to pass the type of the exception just to make sure that I don’t accidently ignore the wrong exception type:

Solution #2 – Using PostSharp

I’ve written about PostSharp in the past it’s an AOP (Aspect Oriented Programming) framework for the .NET world. Using PostSharp you can create an attribute that would execute the decorated method using MethodInterceptionAspect:


public class IgnoreExpections : MethodInterceptionAspect
{
    public override void OnInvoke(MethodInterceptionArgs args)
    {
        try
        {
            args.Proceed();
        }
        catch { }
    }
}

Now all you need to do is to use that attribute on your method:

public class MyClass 
{
    [IgnoreExpections]
    public void MethodThatThrowsException()
    {
        throw new Exception();
    }
}

Of course you can pass specific exception types via the attribute’s constructor and from there the sky is the limit.

One final note

Just because you can doesn’t mean you should. So before you decorate all of your methods with IgnoreExceptions think if it’s a good idea – there is a place and time for anything – even ignoring exceptions.
Related Posts Plugin for WordPress, Blogger...