When you’ve got a hammer…

… everything looks like a nail.
Type classes. In C#. Because I’ve got a hammer. Haskell gave it to me.

A what?

… a type class is a type system construct that supports ad hoc polymorphism. This is achieved by adding constraints to type variables in parametrically polymorphic types.

Uh… in English…

If you’re coming from an OO perspective (as I am) you can think of type classes as rather like an interface; with the additional ability to provide default implementations for their functions – making them perhaps rather more like abstract classes without fields in a type system with multiple inheritance, but that sounds more clunky.

Rather to be expected, the idea of type classes doesn’t fit well into an language based heavily around the OO-paradigm (like C#) but I thought it might be instructive (to myself even if to nobody else) to see how we could model something akin to them. What we’ll be doing below doesn’t interact nicely with inheritance and polymorphism, they they are somewhat orthogonal approaches and their intersection is at best confusing. It’s also a fairly terrible idea, but that should go without saying…

One way to describe what we’re trying to achieve would be to say that we wish to attach behaviours to a type not via its instances, but through a separate ‘static’ definition for that type. We also want membership to a type class to be enforced at compile time, and to be able to be members of multiple type classes simultaneously.

Equality for all (that opt-in)

I’m going to focus on the Eq type class here, but will be keeping in mind that this could be extended to other type classes.

First things first, we need a marker interface to declare our type as a member of the type class.

interface IEq { }

Next, we’re going to need a way for types to provide specific behaviour. It sound a bit odd to say, but inheritance seems the obvious choice here: it provides us the ability to override functions and is built-in to the language. One thing that we can’t restrict here is deriving classes adding fields/state – there are ways to enforce that but they’re more work and this is perfectly instructive for now.

public abstract class EqImpl<T>
    where T : IEq
    // we can require functions to be overridden...
    public abstract bool Equals(T a, T b);

    // or provide some default behaviour...
    public virtual bool NotEquals(T a, T b)
        return !Equals(a, b);

Now, we need a way for a type to actually specify its behaviour once it has declared itself a member of a type class, and a way for consumers of the type to access that behaviour.

For a class Foo we’ll do this by instantiating a ‘EqImpl‘ and storing it for use by consumers of Foo… this will obviously have to be done at runtime – if we could do this sort of thing at compile-time, we’d essentially already have our type classes already! The obvious place to do this is in the static constructor for Foo as we know this is going to be executed exactly once, and before Foo is ever instantiated. Again, we are unable to actually enforce that an implementation has actually been provided – we could provide a complete default implementation, but for simplicity I’ve not done that here.

public static class Eq<T>
    where T : IEq
    private static EqImpl<T> impl;

    public static bool Equals(T a, T b)
        return impl.Equals(a, b);
    public static bool NotEquals(T a, T b)
        return impl.NotEquals(a, b);

    public static void Register(EqImpl<T> impl)
        Eq<T>.impl = impl;
public class Foo : IEq
    static Foo()
        Eq<Foo>.Register(new FooEqImpl());

    public string Name { get; set; }

    private class FooEqImpl : EqImpl<Foo>
        public override bool Equals(Foo a, Foo b)
            return a.Name == b.Name;

Finally, let’s see how to actually consume our Eq ‘type class’

public void Compare<T>(T a, T b)
    where T : IEq
    if (Eq<T>.Equals(a, b))
        Console.WriteLine("equal :)");
        Console.WriteLine("not equal :(");


One thing that was really highlighted for me, and something I’d never really thought about before, was that methods like

void M(IFoo a)

have lost an large amount of the compile-time type information that could have been available to them. To keep that information we can write

void M<T>(T a) where T : IFoo

which is likely almost exactly what we’d do if we needed T : IFoo and T : IBar; although given how much more verbose and clunky it is to write code like this, it’s fairly clear (a) why we don’t and (b) that it’s probably not idiomatic.

The more you know…

After writing this I discovered this correspondence of type classes using C++ template which shows some similarities to what I was attempting to achieve here using less powerful C# generics. So while all of this is all clearly a terrible idea, at least I feel that I’ve not inherently failed to understand type classes.

It’s a trap!

I recently read a great article about traps in software development
The post itself was summarising ‘System Thinking – A Primer’ by Dana Meadows.
And to help it sink in, I’m going to summarise the summary here.

A trap is roughly defined as a system structure that tends to result in problematic behaviour.
In my own vernacular, I’d probably call it a process that doesn’t help us fall into the Pit of Success

Policy Resistance

Occurs when there are conflicting needs between multiple parties in a system.
It’s a tug of war, and the harder you pull the harder the other party pulls back.
You’re never going to get anywhere, but you’re going to expend a lot of energy doing it.

Tragedy of the commons

Caused by misplaced, often short-term, incentives leading to sub-optimal long term results.
E.g. fishermen are incentivised to over-fish, depleting stocks and destroying their own livelihood.
E.g. constantly adding new features at the expense of a maintainable codebase.

Drift to low performance

When we base our projections on perceived current state rather than an objective reality or pragmatic ideal…
… Goals can erode over time leading to a downward spiral.
E.g. code perceived as bad can lead to maintenance efforts being “just good enough”, further lowering its quality.


An arms race due to the perceived state of a competitive system – the opposite of ‘drift to low performance’.
Often occurs when competition is misguidedly used as a motivator.
What happens when we’re all measured against some proxy? The measurements will improve, that’s what!

Success to the successful

The rich get richer while the poor stay poor.
Becomes more important to appear to be successful than to actually be successful.
Can stifle innovation due to fear of the repercussions of failure.

Shifting the burden to the intervenor

When the solution to a problem undermines the capacity of the system to maintain itself.
E.g. solving an alcohol addiction by having another drink, it certainly helps (in the short term).
E.g. bug fixing by patching over the symptom, leaving the underlying cause un-addressed.

Rule beating

When rules cause a system to behave in a distorted way, nonsensical in the absence of the rules.
Often due to following the letter rather than the spirit of a law.
E.g. lengthy sign-off required for projects estimated over X… most work becomes estimated at X-1.

Seeking the wrong goal

You have a problem with rule beating when you find something stupid happening because its a way around the rule. You have a problem of wrong goals when you find something stupid happening “because it’s the rule”. ~Dana Meadows

Often occurs when progress towards a goal is evaluated via a proxy measure rather than the goal itself.
When the proxy measure becomes the goal itself.
E.g. King Midas sought the wrong goal – turning everything you touch into gold doesn’t necessarily make you rich.

F#ing brilliant

I think there’s a time for all of us when we sat down to write a piece of code and it worked perfectly first time, and we thought to ourselves that perhaps we might just make developers of ourselves yet – shortly before we found an edge case that wasn’t covered, or irreparably broke everything with our overconfidence.

I’ve recently been going through Project Euler problems again – having solved a great many of them in C# – and solving them in F#. And it’s been amazing. That feeling of things working first time has become more commonplace than it has any right to be, particularly in a language that I’m (relatively) unfamiliar with and when I’m writing code with no IDE niceties (LinqPad); and since I’m fairly certain that I haven’t become insanely competent at overnight, I can’t help but feel that it can only be attributed to the language and paradigm itself.

If I wasn’t before, I’m certainly feeling the love for F# now.

For example…

Problem 13 is incredibly simple if you have an arbitrary-sized integer type, and while I could easily use Math.bigint, I thought it might be a nice exercise to create my own. Now, the code below may not be the prettiest in the world, and it certainly isn’t the most efficient, but for something that I knocked together in a few minutes in my spare time without taking too much care over… it worked first time! (Well… almost anyway… the first time around I forgot the case where the digits had all been dealt with but carried wasn’t zero.) Hopefully that doesn’t undermine my point too much, because I’ve truly been impressed by how much I feel helped rather than hindered by the language.

type BigNum (digits: int list) = 
	// digits: list of decimal digits smallest-biggest
	static let carryDigits digits = 
		let rec carryDigits digits processed carried = 
			let getDigitAndCarry next = 
				next % 10, next / 10
			match digits with
			| [] -> 
				match carried with
				| 0 -> processed // all done and nothing more to carry
				| _ -> // digits all done, but still carrying left
					let digit, carriedNext = getDigitAndCarry carried
					carryDigits digits (digit :: processed) carriedNext
			| _ -> // keep going...!
				let next = (List.head digits) + carried
				let digit, carriedNext = getDigitAndCarry next
				carryDigits (List.tail digits) (digit :: processed) carriedNext
		carryDigits digits [] 0 |> List.rev
	member this.digits = carryDigits digits
	static member Create (s: string) =
		let numStringToList (s: string) = 
			|> Seq.map (string >> Int32.Parse)
			|> List.ofSeq
			|> List.rev
		let digits = numStringToList s
	static member (+) (a: BigNum, b: BigNum) =
		let matchLengths list1 list2 = 
			let extend list toLength = 
				let lengthToAdd = max 0 (toLength - List.length list)
				let zeroes = [for i in 1..lengthToAdd -> 0]
				list @ zeroes
			let list1' = extend a.digits (List.length list2)
			let list2' = extend b.digits (List.length list1)
			list1', list2'
		let resultDigits = 
			matchLengths a.digits b.digits 
			||> List.zip 
			|> List.map (fun (a,b) -> a + b)
			|> carryDigits
	override this.ToString() =
   		List.fold (fun acc x -> string(x) + acc) "" digits

i.Take(a); break;

I’ve been away from work for the last five weeks, and since most of that time has been abroad I’ve been completely out of the loop. This is probably the longest time in my career that I’ve gone without giving more than a cursory thought to the world of development.

Getting back into the swing of programming has been hard over the last few days, forcing my brain back into useful patterns of thinking and feeling ‘switched on’ or ‘in the zone’ are never things I’ve really struggled with, so this has been something of an education!

Catching up on more than a month’s worth of releases/updates/news has been less overwhelming than I had thought it would be though, I just can’t decide if there’s not been a great deal happening recently, or whether I’m used to keeping myself more up-to-date than is strictly necessary…

Performance anxiety

Given the choice I’d happily avoiding doing almost any UI work at all, but working in a small team means being comfortable working on any part of the stack. I recently had some performance problems in WPF, to which my initial reaction was hands-to-head, head-to-desk, groan; but a problem is a problem and that’s a major part of why I chose a career in programming, so it was time to get investigating.


We have a fairly simple list-detail set up using a Caliburn.Micro conductor, a TreeView for the list and <views:Component cal:Bind.ModelWithoutContext="{Binding}"/> for the detail. We were seeing performance problems when moving between certain items, the UI would hang for perhaps a couple of hundred milliseconds: not long enough to be disastrous, but easily enough to be jarring to the user and to make any transitions far from smooth. My immediate candidate for suspicion was the DataGrid. The problems seemed to only occur when moving to a detail view containing a DataGrid, and my suspicions became more founded when the problem worsened as the detail view contained more than one DataGrid (although strangely it seemed to matter little how much data / how many rows each DataGrid actually contained).

It looked as though my problem was that of re-binding each DataGrid as we moved between items.


The idea was to keep the view for each item alive and bound – but out-of-sight – rather than either destroying and creating a view instance each time or re-using and re-binding.

Whether this turns out to be the best solution in the longer-term remains to be seen as it’s clear to see that we’ve caused ourselves a memory leak by keeping the view alive for every item ever selected; although for the specifics of it’s current usage this won’t be an issue as the number of items is limited to relatively small number.


Create a control with a CurrentItem property binding to the selected item and an ItemTemplate property that will be used to create views for new items, caching and re-using them for items that have already been selected. This doesn’t help the performance the first time that an item is selected, but each subsequent selection is essentially instantaneous and provides a much improved user experience.

It actually turned out relatively easy to implement this – as you can see below – and in our production version we’ve helped eliminate and memory issues by hooking into Caliburn’s Deactivated event (when WasClosed == true) to avoid holding on to unnecessary view instances.


public class ContentHost : ContentControl
	#region Fields

	public static readonly DependencyProperty CurrentItemProperty =
			new PropertyMetadata(

	public static readonly DependencyProperty ItemTemplateProperty =
			new UIPropertyMetadata(null));

	private readonly Grid contentGrid;
	private readonly Dictionary<object, ContentPresenter> items;
	private UIElement currentView;


	#region Constructors

	public ContentHost()
		this.contentGrid = new Grid();
		this.items = new Dictionary<object, ContentPresenter>();
		this.Content = contentGrid;


	#region Properties

	public object CurrentItem
		get { return (object)GetValue(CurrentItemProperty); }
		set { SetValue(CurrentItemProperty, value); }

	public DataTemplate ItemTemplate
		get { return (DataTemplate)GetValue(ItemTemplateProperty); }
		set { SetValue(ItemTemplateProperty, value); }


	#region Methods

	private static void OnCurrentItemChanged(
		object sender,
		DependencyPropertyChangedEventArgs args)
		var contentHost = (ContentHost)sender;

		var newItem = args.NewValue;
		var view = contentHost.EnsureItem(newItem);

	private void SwapCurrentViewFor(ContentPresenter view)
		currentView = view;

	private ContentPresenter EnsureItem(object currentItem)
		ContentPresenter view;
		if (!items.TryGetValue(currentItem, out view))
			view = new ContentPresenter();
			view.Content = currentItem;
			view.ContentTemplate = ItemTemplate;
			items.Add(currentItem, view);

		return view;

	private void BringToFront(UIElement uiElement)
		uiElement.Visibility = Visibility.Visible;

	private void SendToBack(UIElement uiElement)
		if (uiElement != null)
			uiElement.Visibility = Visibility.Collapsed;


Refactoring Cassowary

Now the work begins…
As I mentioned before, my aim is for this codebase to become:

clean, modern, idiomatic, tested

If Refactoring and Working Effectively with Legacy Code have taught me anything, the first step is to get tests in place so that we can “Cover and Modify” and not have to “Edit and Pray”. There are a number of ports of the Cassowary engine out there (Python, JavaScript) and I was able to get a decent amount of tests written very quickly by porting their existing test suites to C#. This left me with a lot of integration / end-to-end tests, but with relatively few unit tests – for those there was no free lunch.

Let’s get typing

After tests, the first item on the agenda was to improve the type-sanity of the code.
It made heavy use of ArrayList and Hashtable (no generics in sight) and had a lot of casting scattered throughout the code. Replacing the above with List<T>, Hashset<T>, and Dictionary<TKey,TValue> would make the code clearer, cleaner, and safer to work with. I’m a big fan of letting the compiler / type system do as much of the work as possible – it’s much less prone to idiocy than me.

foreach (var idiom …

The next change was another relatively straightforward one: be more idiomatic.
For example, in C# foreach loops are more idiomatic than for loops, and certainly more idiomatic that the direct use of IEnumerators that was to be found in the original code! As I mentioned before, this was a port from a Java implementation of Cassowary and you could tell – it felt like Java. Using bool Try...() methods rather than returning null; properties instead of Get... and Set... methods; all changes to make this codebase feel more like C# and to help future developers (including myself) fall into the pit of success.

Change is tough

And I’m not talking about the refactoring… I’m talking about mutability.
The original code had a lot of publicly mutable state, with comments warning that it shouldn’t be modified when x, y, or z – at least there were comments! Some of the very first steps to tackle this were simply making this internal/protected/private, but that was quickly followed up by removing as much inappropriate mutability as possible.

Currently I’m still wrangling with a few spots of unwanted mutability right in the heart of the solver that are turning out to be a little more stubborn than the rest.


From Wikipedia:

Cassowary is an incremental constraint solver that efficiently solves systems of linear equalities and inequalities. Constraints may be either requirements or preferences. Client code specifies the constraints to be maintained, and the solver updates the constrained variables to have values that satisfy the constraints.

As far as I can tell, the Cassowary solver has been in existence for almost 20 years but there is – as yet – no modern, idiomatic .NET port available.

I felt that it was about time to change to that.

On the shoulders of…

There is an existing .NET port of the Cassowary solver, however from its readme:

Cassowary.net [1] is a port of the Cassowary constraint solving toolkit [2] to the .NET platform. It is based on the Java version by Greg J. Badros, which in turn is based on the Smalltalk version by Alan Borning.

A port of a port of a port. Examining the code we find that it appears to have been ported directly/naively from Java, which has resulted in a lot of non-idiomatic code: no use of of generic data structures, direct manipulation of enumerators, et cetera. That’s not to say that it’s a bad port, simply one that isn’t written in modern C# (forgiveable since it was written almost 10 years ago); and for me, one that I don’t think I’d particularly enjoy interacting with.

So this is my starting point for creating a clean, modern, idiomatic, tested .NET Cassowary constraint solver.

A fork has been created, now the real work begins…


I’ve recently started mindfulness meditation; it seems to be mentioned everywhere you turn at the moment, so I though I’d give it a try. One of the key ideas is to be a passive observer to your thoughts: not trying to stop them, not chasing after them, but simply watching them pass by. By practising impassive observation, we are supposed to be able to more easily step away from problems / situations / stresses in day-to-day life.

We’ve all had the realisation at some point, that for our current situation the best – and possibly only – thing to do is simply to take a step back, take a deep breath, and (in the words of Frozen) let it go.

I’m led to believe that mindfulness meditation has various well supported benefits from reduced stress to increased happiness – and I can certainly believe that to be the case – but I’ve found that it has really helped me to notice when I need to stop coding and go for a break. It sounds like a minor thing, but it can be all too easy to ‘fall down the rabbit hole’ and keeping mashing the keyboard while not actually being productive when writing code. Knowing when to step back, take stock, and look at the bigger picture is an incredibly important skill for a developer looking to produce any kind of complex system.

I know developers that spend a lot of time and effort looking after their physical health, and we are all very much aware of the problems that such a sedentary job can cause; but I don’t think we spend enough time considering our lifestyles’ impacts on our mental health. Particularly with our industry’s problems with startup culture, burnout, et cetera (I read a blog post talking about how to effectively work 16+ hours per day as a developer. I thought it was a joke. It wasn’t.) I think that techniques like mindfulness are becoming ever more important in looking after ourselves.

… and ended (as always) with code

Our requirements from an index-type are fairly minimal…

public interface IIndex
	int Value { get; }

… and this would be enough for a number of scenarios, although not one particular scenario that I wanted: being able to construct a typed-index from an int. This operation is useful for being able to expose existing properties of an array as their typed equivalent, in particular I wanted to expose the length of the array in each dimension.

public interface IIndex<TIndex> : IIndex
	where TIndex : struct, IIndex<TIndex>
        TIndex WithValue(int value);

The above is then used in conjunction with the fact that T : struct implies T : new() to essentially gain a T : new(int) constraint by using var t = new T().WithValue(i). I could call this a tweak on the prototype-pattern but at the end of the day it’s a bit of a hack around the type constraints I’m able to achieve with generics.

Due to index types needing to be structs we can’t use inheritance, making implementing an index type a rather tedious and unpleasant copy-paste affair. While this obviously has plenty of disadvantages, it has the benefit that each index type is free to enabled – or not – methods and operations as it sees fit, for example IComparable<>, IEquatable<>, operator overloads, &c. No more than five or six index types will be created, with some having the requirement to be comparable (e.g. yearA < yearB) and others with the requirement to explicitly not be comparable (e.g. simulation – each is fully independent of all others) so I consider the trade-offs being made here to be acceptable.

Implementing the wrappers for arrays was also a rather tedious job as each rank requires a separate implementation with the correct number of type parameters.

public class StrongArray<TValue, TIndex0, TIndex1> : StrongArray
	where TIndex0 : IIndex<TIndex0>
	where TIndex1 : IIndex<TIndex1>
	private readonly TValue[,] array;

	public StrongArray(TIndex0 length0, TIndex1 length1)
		: this(new TValue[length0.Value, length1.Value])

	public StrongArray(TValue[,] array)
		: base(array)
		this.array = array;

	public TValue this[TIndex0 index0, TIndex1 index1]
		get { return array[index0.Value, index1.Value]; }
		set { array[index0.Value, index1.Value] = value; }

        public TIndex0 Length0
            get { return new TIndex0().WithValue(array.GetLength(0)); }

        public TIndex1 Length1
            get { return new TIndex1().WithValue(array.GetLength(1)); }

	public TValue[,] Array
		get { return array; }

And, no, I couldn’t think of a better name at the time!

Was it worth it?

For about a day an a half of coding, what Code Metrics tells me is 125 lines of code – with the biggest contributor being a class of helper methods such as Enumerable.Range equivalents – and a very modest performance penalty, this thin abstraction over arrays has had a significant impact on how much information is conveyed by our code and has helped to reduce the amount of time and effort required to understand a piece of code.

It all started with Matlab…

O, for a green field

We’re currently preparing to rewrite a reasonable amount of Matlab into C#. Starting afresh is always enjoyable but rarely sensible, however one of the major reasons for us doing so is that we no longer have the skills to maintain the codebase as it stands. For a start we no longer have any experienced Matlab developers, and for a second the existing code is a glorious combination of spaghetti logic, single-letter variables, and cryptic – and often untrue – comments.

We intend to do the rewrite in stages, moving into the world of C#, Visual Studio, and heaps of testing and refactoring tools as quickly as possible, then incrementing our way to a reliable, performant, maintainable solution. Our first step will be to rewrite the Matlab code into a very simple stripped-down Matlab-like set of classes in C# as verbatim as possible, we’ll use a barrage of regression tests to make sure that is done correctly. Next, we’ll refactor that code from the loosely-typed ‘framework’ we’ve created into arrays where we know types and dimensions &c; during this process we’ll be familiarising ourselves with the code and adding simple structure as we go. Finally, we’ll convert what we now have into idiomatic C#, moving – where appropriate – away from the array-based Matlab-style approach, using the full power of the language and data-structures available to us.

One of the major struggles that we’ve seen with the current code is tracking dimensions. With an array of simulation * year * ... * series * tranche that is being manipulated and combined with other arrays in sometimes unconvential ways and inside thousand-line methods, it becomes almost impossible to know if the second dimension of arrPenIcrPost was year, simulation, or something else entirely.

With this in mind, I wrote a thin wrapper for C# arrays which, along with some helper classes, will allow for ‘strongly-typed’ indexing: for example having an array of double<Sim,Year>[,] so that the dimensions are not referenced simply by int but by custom types. The types of the dimensions will be an integral part of the type of the object, will be enforced by the language, and will as a consequence be impossible to mistake.

Performance anxiety

My main concern with doing this was that of performance, I truly wasn’t sure how well the code I was writing would be perform. I could certainly see ways in which I hoped the code would be optimised, such as inlining the underlying value of the structs being used as indexes; but I could also see potential problems, mostly around the boxing of value types and the overhead of pointer-chasing.

To my delight (and slight surprise) the performance overhead could be made extremely minimal with relatively little work; the most important factors that I hit while developing were using structs for the index types, avoiding inheritance and virtual methods in certain situations, and using class-level generics rather than method-level generics.
The first is fairly obvious and was the approach I took anyway, I simply changed to classes to see what impact it would have; the second is again relatively straightforward, vtables and all that; the third was slightly more surprising, and I believe has to do with the optimiser being able to avoid boxing value types when accessing them through an interface if the entire class is generic.

There will be code

That’s rather a lot of text without so much as a hint of code. Next time I’ll be looking at the code that actually achieves all of the above!