If you have been reading some of the posts in my blog, you will know that sometimes I present a problem and a solution in an article which takes you through the thought process from making the first straightforward solution through refining that solution into a hopefully better code design. This is one of those posts.

Let’s talk a bit about separation of concerns. One scenario that I stumble upon fairly frequently when coding is the need for some code that should perform a task at a time based interval. This is nothing strange, and it is not very hard to achieve. But it still does present some challenges.

In order to have a simple example, let’s say that we have a TimeTeller class. It will, at a certain interval, tell us what time it is:

var timeTeller = new TimeTeller(
    timeString => Console.WriteLine("The time is now {0}", timeString))
{
    Interval = TimeSpan.FromSeconds(1)
};
timeTeller.Start();

It takes a callback method which will be called at the given interval, providing a string with the current time. Nice and simple. But it has two distinct drawbacks:

  • It’s not a very testable design, because of its asynchronous nature
  • The TimeTeller class now has two concerns: telling time, and maintaining an interval mechanism

First, let’s look at a first implementation of the TimeTeller class, as it is being used above:

public class TimeTeller
{
    private readonly Action<string> timeStringCallback;
    private TimeSpan interval;
    private Timer timer;

    public TimeTeller(Action<string> timeStringCallback)
    {
        if (timeStringCallback == null) throw new ArgumentNullException("timeStringCallback");

        this.timeStringCallback = timeStringCallback;
    }

    public TimeSpan Interval
    {
        get
        {
            return interval;
        }
        set
        {
            interval = value;
            if (timer != null)
            {
                Start();
            }
        }
    }

    public void Start()
    {
        if (timer == null)
        {
            timer = new Timer(state => TellTime());
        }

        timer.Change(Interval, Interval);
    }

    public void Stop()
    {
        if (timer != null)
        {
            timer.Dispose();
            timer = null;
        }
    }

    private void TellTime()
    {
        timeStringCallback(DateTime.Now.ToString("HH:mm:ss"));
    }
}

As you can see, most of the code in the class is actually not about telling time, but rather about maintaining the interval using a Timer. In this code, telling time is more of a side effect than anything else. Also, if I would want to test this, it would involve some sort of waiting mechanism:

using (AutoResetEvent waitHandle = new AutoResetEvent(false))
{
    var timeTeller = new TimeTeller(s => { waitHandle.Set(); });
    timeTeller.Start();
    Assert.IsTrue(waitHandle.WaitOne(TimeSpan.FromSeconds(5)), "Callback method was not invoked.");
}

This is not overly complicated, but as a test it has one flaw: it can fail for reasons that are not related to our code. If the build server happens to be under great pressure (or just very slow), perhaps the code is not executed as fast as we expect so the wait handle times out. Our code may be perfectly correct, but the test still fails. I am strongly of the opinion that tests should be designed in a way so they should fail only if there is something wrong with the code of the application, not because of anomalies in the surrounding environment.

Now my code base has two problems. The test that is not optimal, and the fact that TimeTeller violates the Single Responsibility Principle.

In the Solid Responsibility Principle, a responsibility is sometimes described as a reason to change. The TimeTeller class in its current design may change for more than one reason: if we want to change how it is triggered, and if we want to change how it tells time.

So, first I want to remove the trigging mechanism from the TimeTeller class. To do this, I design an ITrigger interface:

public interface ITrigger
{
    void RegisterAction(Action action);
    void UnregisterAction(Action action);
}

It’s extremely simple; I can register an Action that will be invoked by the trigger, and I can unregister the Action. Notice how this interface says nothing at all about how the code will be trigged. From this point of view, that is of no importance. That is somebody else’s concern. Now I can refactor the TimeTeller class to use an external trigger instead of maintaining its own trigging mechanism:

public class TimeTeller
{
    private readonly Action<string> timeStringCallback;
    private readonly ITrigger trigger;

    public TimeTeller(Action<string> timeStringCallback, ITrigger trigger)
    {
        if (timeStringCallback == null) throw new ArgumentNullException("timeStringCallback");
        if (trigger == null) throw new ArgumentNullException("trigger");

        this.timeStringCallback = timeStringCallback;
        this.trigger = trigger;
    }

    public void Start()
    {
        trigger.RegisterAction(TellTime);
    }

    public void Stop()
    {
        trigger.UnregisterAction(TellTime);
    }

    private void TellTime()
    {
        timeStringCallback(DateTime.Now.ToString("HH:mm:ss"));
    }
}

Notice how this class now has a much more focused design. There is a lot less code that is about how to do stuff. Let’s say it has a lower “how-to-what” ratio.

Great, but what about the trigger part? The code that I just ripped out of the TimeTeller class needs to go somewhere, right? Right. I need to implement some sort of interval based trigger. Already at this point I realize that I will want to implement a couple of different triggers. I want the interval trigger to use with my TimeTeller class. I will also want to make some sort of direct trigger that I can use to directly trig the functionality, which might be very useful in unit tests in order to “fake” the interval based trigging. So, I put the most basic stuff in a base class:

public abstract class TriggerBase : ITrigger
{
    private Action action = () => { };

    protected TriggerBase()
    {
        Enabled = true;
    }

    public bool Enabled { get; set; }

    public void RegisterAction(Action action)
    {
        this.action = (Action)Delegate.Combine(this.action, action);
    }

    public void UnregisterAction(Action action)
    {
        this.action = (Action)Delegate.Remove(this.action, action);
    }

    protected void TrigInternal()
    {
        if (Enabled)
        {
            action.Invoke();
        }
    }
}

This takes care of the bare necessities: it allows me to register and unregister Action callbacks with the trigger, and have them invoked. Note that by using Delegate.Combine and Delegate.Remove, I can register multiple actions with the same trigger, which might be handy. Now, let’s extend the base class to make the interval trigger:

public class IntervalTrigger : TriggerBase
{
    private TimeSpan interval;
    private Timer timer;

    public IntervalTrigger()
    {
        StartInterval();
    }

    public TimeSpan Interval
    {
        get
        {
            return interval;
        }
        set
        {
            interval = value;
            StartInterval();
        }
    }

    private void StartInterval()
    {
        if (timer == null)
        {
            timer = new Timer(state => TrigInternal());
        }

        timer.Change(Interval, Interval);
    }

    private void StopInterval()
    {
        if (timer != null)
        {
            timer.Dispose();
        }
    }
}

You can see how the IntervalTrigger implementation is very much like the code we removed from TimeTeller. Now when we use the TimeTeller class, we simply provide an IntervalTrigger that will take care of calling into the TimeTeller at the given interval:

var timeTeller = new TimeTeller(
    timeString => Console.WriteLine("The time is now {0}", timeString),
    new IntervalTrigger { Interval = TimeSpan.FromSeconds(1) });
timeTeller.Start();

Now that we have separated the concerns how to call code at a given interval and how to tell time, we also get a much nicer setup for testing. As I mentioned previously, I was planning to implement some sort of direct trigger that can be used for instance in tests:

public class DirectTrigger : TriggerBase
{
    public void Trig()
    {
        TrigInternal();
    }
}

By passing a DirectTrigger to TimeTeller, I can now easily control exactly when it is being called into, and it is done in a synchronous manner. The asynchronous test above can be rewritten into a synchronous one instead:

bool callbackWasInvoked = false;
var trigger = new DirectTrigger();
var timeTeller = new TimeTeller(s => { callbackWasInvoked = true; }, trigger);
timeTeller.Start();
trigger.Trig();
Assert.IsTrue(callbackWasInvoked, "Callback method was not invoked.");

This test is not time sensitive anymore, but will be very tolerant for slow build environments and such.

One nice thing about having moved the whole trigging concern out of the TimeTeller is that we can now allow the code to be trigged in new ways, without the TimeTeller even knowing about it. I used this fact when rewriting the test for instance. But what if I suddenly got the requirement that the TimeTeller should be able to tell time at a given interval, but there should also be a possibility to invoke it directly, at will. As it happens, this is now very easy to achieve. I just make a new ITrigger implementation:

public class CompositeTrigger : TriggerBase
{
    public CompositeTrigger(params ITrigger[] triggers)
    {
        foreach (ITrigger trigger in triggers)
        {
            Add(trigger);
        }
    }
    public void Add(ITrigger trigger)
    {
        trigger.RegisterAction(TrigInternal);
    }

    public void Remove(ITrigger trigger)
    {
        trigger.UnregisterAction(TrigInternal);
    }
}

This gives me the option to combine any triggers I want, and the TimeTeller is still unaware:

DirectTrigger directTrigger = new DirectTrigger();
IntervalTrigger intervalTrigger = new IntervalTrigger
	{
		Interval = TimeSpan.FromSeconds(5)
	};
CompositeTrigger trigger = new CompositeTrigger(directTrigger, intervalTrigger);
var timeTeller = new TimeTeller(s => { callbackWasInvoked = true; }, trigger);

This will cause TimeTeller will be invoked once every 5 seconds, and whenever any code calls directTrigger.Trig(). In the sample project that I have linked to in the end there is also an AsyncTrigger which is a flavor of the DirectTrigger that will invoke the target callbacks on a separate thread, so that the calling code is not blocked.

To sum it up, by separating concerns like this you will hopefully end up with a code design where both types and tests are more focused on their primary task. There will be more what and less how in the code.

Download sample code from my BitBucket repository.

kick it on DotNetKicks.com


I am working for a great consultancy company called Diversify, located in Sweden. We are hiring skilled .NET developers. If you are interested, don't hesitate to get in touch with me.

Say the word static to a developer and see what happens. If nothing at all happens, you should be a little bit worried. As a bare minimum you should get some sort of reaction indicating caution. I keep bumping into scenarios where the presence of static doesn't really solve any problems, but instead just makes things harder.

First, I would like to make it clear that, at least to me, static comes in two forms. Or, well, three forms to be more precise.

Static functions

There is something called a pure function.

A function is said to be pure if it always returns the same result for the same input, and if it has no observable side effects.

If the above statement is true it should not make any difference whether the function is static or not. Since it should return the exact same result every time for a given input, it can’t use any other data for its work, since any other data may mutate over time. In that sense, pure functions can just as well be made static.

It's important to notice both criteria for a pure function:

  • Always returns the same result for the same input
  • No side effects

As an example we can look at the DateTime structure in .NET. It has some static methods and properties. If we look at DateTime.Compare we can see that it takes two DateTime values as input, and returns a boolean, indicating whether the two values represent the same instant in time or not. This method will always give the same result for the same input. If you pass in two DateTime values that represent the same time, it will always return true. Also, it will have no side effects, it will not modify any state in your system, or in the objects passed to it.

The property DateTime.UtcNow is also static, and will also not have any side effects by modifying anything. But it's not a pure function, since it will return a new value on each call (at least for the purpose of this discussion; in reality it may return the same value on several calls if they are done within a very short time frame).

As we can conclude is that DateTime.Compare can be easily tested while DateTime.UtcNow cannot be easily tested.

Static state

If we move on to static state we are talking about data that is shared by all code in a program, and with state it’s a completely different ball game. State is mutable. What one part of the system does, will affect other parts of the system. The results of various operations is “sticky”, it remains in the system.

The one key area where I tend to come across the most trouble in relation to static state is when writing tests for software, and I like my tests. They help me sleep at night. Writing reliable unit tests for software that has static state is hard. If there is no way to mock that state away, it borders to the impossible. State from one test may “leak” to the next test being executed. A common sign of this is when you have a suite of tests where some tests fail when run as part of the suite, but pass when run separately.

Introducing static state also has an effect on life-time management of objects, of course. It may very well be that for the system that you are making, there really should be only one instance of this data in one session. However, this is typically related to the life-time and scope management of the instances of that type, not to the functionality in the type itself.

Also, when introducing static state you pretty much remove the possibility to run unit tests in parallel, since they will suddenly interfere with each other.

Design implications

When you decide to have a type with internal static state, you are making decisions for the user of that type that the user can’t do anything about. Consuming code is stuck to relate to the fact that there is static state in there. This may work well for a given scenario, but not in another. In this perspective, it’s obviously a lot more useful to not make such decisions on behalf of the consuming code but instead leave that up to the consumer. If a static usage scenario fits the context then that option is still available to the consumer.

TL;DR

Please, please pretty please: with the exception of pure functions, do not make types or functions static unless it actually is the only way to solve your problem. It is much more likely to create problems than to solve one.


I am working for a great consultancy company called Diversify, located in Sweden. We are hiring skilled .NET developers. If you are interested, don't hesitate to get in touch with me.

If you already know and use the DebuggerDisplay you can fast-forward to the evil stuff. Otherwise, keep reading to learn a new useful tool and also how not to use it.

Introduction to DebuggerDisplay

Let’s start with a quick demonstration of when and how DebuggerDisplay is useful. Let’s say you have some code like this:

public class Person
{
    public string Name { get; set; }
}

public class Employee : Person
{
    public string Department { get; set; }
}

Now, let’s say that you have a variable in your code that references an IEnumerable<Employee>. If you watch that value using the debugger, it can look like this:

Employee list without DebuggerDisplay

We can see that there is a sequence of Employee objects, but not much more. If we wanted to verify that there is an Employee instance with the name “Sophie Jackson” we would need to expand each object to examine its Name property which is a tedious task to say the least. This is where DebuggerDisplay can help out. By decorating the Employee class with the DebuggerDisplay attribute, we can control how the debugger will display the object:

[DebuggerDisplay("Employee [Name = {Name}, Department = {Department}]")]
public class Employee : Person
{
    public string Department { get; set; }
}

Now, if we check the value of the employees variable as above, it will instead look like this:

Employee list with DebuggerDisplay

Now it’s obviously a lot easier to find the employee called “Sophie Jackson”. Just browse through the list and you will quickly see whether that Employee instance is there or not.

More advanced usage

The debugger will evaluate the expression found in the DebuggerDisplay attribute and show the value. Can this be used to do more complex things than to get a value from a property? Yes, it can. However, I urge you to resist the temptation to do fancy stuff here. The DebuggerDisplay attribute can have unwanted side effects, as we will see further down in this article. Let’s look at an example:

[DebuggerDisplay("Employee [Name = {Name}, EmpYears = {((int)(System.DateTime.Now - EmploymentDate).TotalDays / 365)}]")]
public class Employee : Person
{
	public string Department { get; set; }
	public DateTime EmploymentDate { get; set; }
}

Again, watching the employees variable in the debugger:

Employee list with DebuggerDisplay expression

You can see how each object is presented with a number that is calculated based on the difference between the current date and EmploymentDate, converted to years and cast to an int.

Now, while this is a very useful feature, it should be used with care. If we consume the class used in this example from code written in VB.NET this is what we get:

VB.NET cannot interpret C# expression

As you can see, the debugger now fails to evaluate the expression calculating the number of years. The reason is explained in the documentation:

Expressions are evaluated by the expression evaluator of the language of the current stack frame and not by the evaluator of the language in which the expression was written. This can cause unpredictable results when the languages are different.

So instead of the evaluated expression, you get an error message. The same happens if you for instance have a typo in the property name:

Employee list with misspelled property

As we can see, the DebuggerDisplay attribute is very useful, but should be used to evaluate very simple and “cheap” values. Personally I only tend to use it to fetch values from property getters that just returns the value from a backing field with no other logic being involved. Above all, make sure to not have DebuggerDisplay invoke any code that till mutate any state…

How DebuggerDisplay may crash your debugger

As we have seen from the above examples it’s not very hard to make the debugger fail to evaluate the expression in a DebuggerDisplay attribute, but it does so in a nice and forgiving manner: it simply replaces the value placeholder with an error message instead of the evaluated expression. However, it is possible (even simple) to write an expression that instead will make you see this:

Employee list with crashed debugger

Now, that is not nice. I actually experience this in a project where this error started to appear among the developers and where we at first couldn’t identify what caused the environment to crash, since there (at first) were no obvious pattern of where the crash happened. After a while one of the team members found the offender. It was a DebuggerDisplay attribute crafted like this:

[DebuggerDisplay("Employee [Name = {base.Name}, Department = {Department}]")]
public class Employee : Person
{
    public string Department { get; set; }
    public DateTime EmploymentDate { get; set; }
}

Note the base.Name construct. This is what caused the debugger to crash. I found this somewhat surprising (perhaps even to be considered a bug in the debugger?), especially since it works well to use the construct this.Name.

kick it on DotNetKicks.com


I am working for a great consultancy company called Diversify, located in Sweden. We are hiring skilled .NET developers. If you are interested, don't hesitate to get in touch with me.

The second day of Øredev was started with a keynote by Reginald Braithwaite, called “The Rebellion Imperative”. With a very humble attitude, he delivered a talk with the main message that “If Reg can make it up onto the stage of Øredev, I can [fill in your own blanks]”. He talked about his own background, how he fell in love with coding (including programming in SNOBALL, which seems to be a …peculiar language), and also discussing market dynamics, and what to do (and not to do) in order to be a rebellion on a market. Watch it on Vimeo.

Then I went to listen to Damian Edwards who talked (and demoed) how to make real-time web applications in ASP.NET using SignalR. This is a very interesting library for building multi-user web applications where you want to enable users to get feedback in real-time based on what other users do. Apparently it scales very well and functions well in load-balanced scenarios as well. One thing that I really like with the SignalR team is their efforts in making clients available on varioys platforms, such as iOS and Android. (Video not online yet)

The next person to take on the stage, in the same room as Damian, was Johan Lindfors. His topic was “Windows Phone Development Best Practices” and he shared some insights both about tools and approaches based on personal experience. I got a few good tips on tools that I should look into, such as the MemoryDiagnosticsHelper by Peter Torr, which Johan also has made into a Nuget package. (Video not online yet)

After lunch I went on to listen to Steven Sanderson’s “Build web apps much faster”. During the talk he built (using some pre-cooked code samples) a simple taxi booking web site using the static site generator making a static html/js frontend, and using Azure Mobile Services for the backend. Mobile Services looks quite interesting, but one thing that bothered me was that js code for intercepting calls to the database (for transforming data before inserts for instance) was edited within the control panel in the web browser. This feels like code that I would definitely want to have under source control. That may very well be possible, but it was not demoed during this talk (or during demos of the feature in the Microsoft booth). (Video not online yet)

After streak of rather techincal and relatively high-paced talks, I went on to listen to Billy Hollis talk about “Interaction and Navigation Patterns for Modern User Experience”. This was mainly a walkthrough of various UX design approaches and their uses. Watch on Vimeo.

A few weeks before the conference, Microsoft announced TypeScript. They call it “a language for application-scale JavaScript development” and the aim is essentially to provide a developer experience than many experience with JavaScript. Mads Torgersen, one of the inventors of TypeScript (and also a member of the C# language team) gave a coding-based talk showing some of the features of the language and how it functions. He also pointed out the TypeScript playground, where you can write TypeScript and having it translated to JavaScript in real-time, which seems like a great learning and exploration tool. Watch on Vimeo.

The last regular session for the day that I went to was “Rocking the Enterprise with the Kinect Experience” with Jesus Rodriguez. During his session he demonstrated how to work with the data streams from the Kinect device in order to let a user control a piece of software, and he also showed a couple of business application (mostly sales related) that used the Kinect for user input. Unfortunately the Kinect did not work flawlessly, but it was still a very interesting session where he also used members of the audience (such as myself) to help out with the demos. Watch on Vimeo.

After the dinner break it was time for an evening keynote, which was a talk by Alexander Bard. The title was “The Rebels Come Out Online – what if the Internet is something much bigger than we think?”. This was a very interesting and thought provoking talk, and probably the one talk during the conference that caused the largest amount of discussion afterwards. The talk was rooted in the ideas that has shaped the way we look at our history, suggesting that we are using the wrong perspective when looking at it, and ultimately arriving in what the Internet is doing to our society, and pointing towards the historical reasons for it to happen. Watch on Vimeo.


I am working for a great consultancy company called Diversify, located in Sweden. We are hiring skilled .NET developers. If you are interested, don't hesitate to get in touch with me.