Wednesday, November 26, 2014

Slides from "OWIN and Composable Web Apps" at Campus Days Cph

Here are the OWIN slides from the talk I did at Campus Days Cph today. Enjoy :)

Friday, November 7, 2014

A First Look at C# 6 - Nameof operator

This is the fourth post about the C# 6 features I used when moving Nancy.Linker over to C# 6. The first part was about primary constructors. The second part was about auto properties. The third was about expression bodied members. This one in about the new nameof operator.

The nameof operator

The new nameof operator is a unary operator that takes, as its argument, a type, an identifier or a method and returns the name of the argument. That is, if you pass in the type Uri, you get back the string "System.Uri", if you pass in a variable you get back the name of the variable as a string.

In Nancy.Linker there was one opportunity for using nameof, which I coincidentally think represents a usage of nameof that will become widespread.
In one the private methods in Nancy.Linker there is a null check followed by a possible ArgumentException:

Notice how I am repeating the name of the res variable in a string in order to tell the ArgumentException which argument is in error. With the nameof operator I avoid this duplication and potential source of inconsistency as follows:

Note that in case I rename res and forget to update the usage inside nameof I get a compile error.

Do I Like This?

Yes. It lets me have fewer magic strings.

Wednesday, November 5, 2014

A First Look at Using C# 6 - Expression Bodied Members

This is the third post about the C# 6 features I used when moving Nancy.Linker over to C# 6. The first part was about primary constructors. The second part was about auto properties. This one is about the new expression bodied members feature.

Expression Bodied Methods

I like to break down my code down to short methods. Quite short. So I often have one-liner methods. In Nancy.Linker I had this for instance:

With C# 6 I can make this even shorter because methods that consist of just one expression, can be implemented as just that - one expression .... with a fat arrow in front of it. Like so:

Expression Bodied Properties

I didn't have an opportunity to use any expression bodies properties in Nancy.Linker, but I want to mention them anyway.

Just as single expression methods can be changed to be a fat arrow followed by the expression so can getter only properties that have just one expression in the getter. Note what I said there: Getter only properties can be expression bodied. Properties with setters cannot ... but ... think about it ... what would it mean to set a property consisting of only an expression? There is nothing there to assign to.

Seeing that expression bodied properties are getter only, it stands to reason that you don't have to state the 'get'.
As an example an expression bodied property looks like this:

Do I Like These?

Yes :-)
I like them because they cut down on boilerplate.

Monday, November 3, 2014

The 'Unit' in a Unit Test

How much should a unit test cover? What is the 'unit' which it should test? This seems to be a recurring discussion among developers. And rightly so - I am not going to claim to have the ultimate answer to those questions, but I will address one misconception that I hear repeated time and again, namely that the 'unit' of a unit test is a class in the production code. In this post I will show why this leads to bad testing practices and how thinking of the 'unit' as a unit of functionality leads to a better place.


To illustrate my point I'll play around with the following Employee class from an imagined resource allocation system. The system handles work assignments and can only assign them to employees that
  • do not have overlapping assignments
  • have the necessary skills
  • cost less per hour than the assignment pays
Instances of Employee have a number of work assignments each of which start at a certain date and likewise ends at a certain date. Employees also have a skill set and a minimum hourly cost. Employee instances use these properties to implement the business rules around work assignments, like so:

The implementation of Employee shown here is simplistic. Real business rules would no doubt be more involved. Nevertheless this class serves to illustrate the point.
If we follow the notion that the 'unit' of a unit test is a production class it is reasonable to assume that there is a test class corresponding to Employee and that it could look something like this:

Refactoring Production Code

Even though the employee class is simplistic it still has several reasons to change:
  • Changes to the business rules around matching employee skill set and assignment requirements
  • Changes to the business rules for employee availability, for instance introduction of part time assignments
  • Changes to the business rules around employee cost ans assignment rate
In other words the Employee class violates the Single Repsonsibility Principle.
As a first refactoring lets introduce a SkillSet class capable of comparing a set of skills held by an employee and a set skill needed by a task:

which would change the Employe class to this (hint: The changes are in line 12 and 19):

At this point the existing tests need just one follow one change in its constructor:

After that the tests will pass again and - importantly - they will still cover all our code including the SkillSet class.

Refactoring the Test Code?

The Employee_should class now tests not only the Employee class but also the SkillSet class. If we assume that the 'unit' of a unit test is a production class Employee_should is no longer a unit test. Following this line of thought leads towards two changes to the test code:
  • Mock out the SkillSet in the Employee_should. Typically this involves first introducing an interface on top of SkillSet and then using a mocked version of that in the Employee_should
  • Create a new test class for the SkillSet - Skillset_should

I'm not going to write that code, but I'm sure you can imagine it.

Test Code Smell

If we went ahead and did the refactorings to our test code it would be becoming quite smelly:
  • We would have lost all testing of the collaboration between Employee and SkillSet. This is pretty serious since that is in fact where part of the business rules are upheld. These parts of the rules would effectively become untested.
  • The Employee_should test class would become more complicated by the extra setup of the mocked SkillSet - this might not seem too bad at this point, but quickly becomes unwieldy when dealing with more complicated scenarios
  • The Skillset_should test would not add much - it almost just checks that the framework method IsSubsetOf works.

If we, on the other hand, follow the line of thought that the 'unit' of a unit test is a unit of behavior, we would just keep the unit tests as the are after the introduction of the SkillSet class. This is better because the tests are not hampering the freedom to refactor the production code.


I find it much more helpful to think about the 'unit' in unit test as a unit of behavior. Whether that unit of behavior is implemented in one or more production classes is an implementation detail of the production code.

Friday, September 26, 2014

A First Look at Using C# 6 - Auto Properties

This is the second post about the C# 6 features I used when moving Nancy.Linker over to C# 6. The first part was about primary constructors. This one in about the new auto-property features.

Auto-Property Initializers and Getter-Only Auto-Properties

Just like fields can be initialized from primary constructor arguments in C# 6 so can auto properties. In Nancy.Linker this is used in the Registration class where cuts out a good deal of ceremony.

Furthermore auto properties do not need to a setter anymore. This is very different from autoproperties with a private setter, because an auto-property without a setter is immutable, where as an auto-property with a private setter only protected against code outside of the class mutating it.

The Registration class in Nancy.Linker implements the IRegistrations interace from Nancy, which looks like this:

Notice that this is 3 getter-only properties. Until now you would have implement these either with explicit getters, or as auto-properties with setters. In C# 6 their implementation can follow the interface more closely and as an added bonus the whole class becomes immutable. The code for the Registration class becomes:

I like these 2 features because:
  1. They make creating immutable types in C# a lot easier, which I think we will see a whole lot more of in C# code in the near future.
  2. The cut down on the amount of ceremony needed to implement interfaces like IRegistrations

Sunday, September 21, 2014

A First Look at Using C# 6 - Primary Constructors

Update 2nd October 2014: Yesterdaty primary constructors was pulled from the planned features of C# 6, rendering this post somewhat irrelevant. Sorry, but that's the kind of thing that happens in open development processes.

The other night I moved Nancy.Linker to C# 6 - this is the first part of a summary of what I changed along with quick introductions to the C# 6 features I used. Nancy.Linker is a small library (1 interfaces, 2 production classes, 2 test class), so not everything comes into play there - but the 3 C# 6 features I'm most eager to get, namely primary constructors, auto-property initializers and getter-only auto-properties, all did. For the full overview of C# 6 features visit the language features status page on the Roslyn codeplex site.

Before diving in I will note that this is based on code written using the 'experimental' flag for the compiler that comes with Visual Studio 14 CTP 3. Since this is a pre-release of the compiler things may change, but judging from the language features status page linked above the features described here are fairly stable.

Primary constructors

The first feature I used was primary constructors. In Nancy.Linker only 1 of the production classes and 1 of the test classes have non-default constructors, and they only have 1 constructor each. Classes with 1 explicit constructor are prime candidates for primary constructors, so i gave both a primary constructor.

Primary constructors add new C# syntax for declaring a constructor. While multiple constructors are still allowed only one of them can be the primary one. From the outside a primary constructor is no different than any other constructor; its primary-ness is only visible inside the class. The declaration of a primary constructor is part of the class declaration where an argument list is added:

which is equivalent the old ResourceLinker constructor:

Once a primary constructor is declared the variables in the argument list are available for initializing fields and properties in the class. In the ResourceLinker class the old constructor assigned the two constructor arguments directly to private fields. With primary constructor syntax this becomes:

I like this for two reasons.
  1. By pulling the constructor argument list all the way up to the line declaring the class primary constructors place more emphasis on this list. I find that the constructor argument list is quite important, because it shows what is needed to create an instance of the class. Particularly so if you use DI and prefer constructor injection.
  2. It saves a few lines of trivial initializtion code.

Primary Constructor Bodies

My previous experience with primary constructors is from Scala in which everything between the open curly brace at the start of the class and the closing one at the end is the body of the primary constructor. You can put arbitrary code into the class definition and it will run when instances are created. In my experience this is done fairly often in Scala code, and it is a feature I've been happy with in Scala. In C# 6 adding is a body to a primary constructor is - in my opinion - somewhat less elegant because it requires you to add a scope somewhere in the class where all the primary constructor body code is placed.

The tests for Nancy.Linker uses a small NancyModule called test module, which sets up a few routes, that the tests then use. Before that class looked like this:

Take line 8 as an example. This is not simlpy an assignment to a field or a property. Therefore it has to be part of the primary constructor body, so moving this class over to having a primary constructor means turning it into:

See that pair of curly braces around the constructor body? That is that extra scope delimiting the body of the primary constructor.

I still like the changes to this class for the same reasons as stated above, but I don't like the necessity of putting all the primary constructor body code into a scope because:
  1. It is less flexible than the Scala counterpart, because all the code has to be together.
  2. Aestetics: The code is at an extra level of indentation and has to be surrounded by a pair of somewhat dangling braces.

Saturday, August 30, 2014

Using Nancy.Linker with Razor Views

First things first: I recommend that you use Nancy.Linker to generate link in the route handler not the view code, as described in my last post. If you insist on generating the links in the view code here is how to make Nancy.Linker work with Razor views.

Firstly you need to pass an instance on IResourceLinker and the NancyContext to your view. This works just like passing any other object from the handler to the view  - in your Nancy module you have your route handler pass the IResoureLinker and NancyContext objects as part of the model to the view you want to render:

The NancyContext must  passed along with the IResourceLinker, since Nancy.Linker needs it to generate links. Once you've done this you are almost ready to use Nancy.Linker in your Razor code, but first you need a little bit of web.config gymnasitcs. This is because IResouceLinkker returns System.Uri objects, which Razor does not know about unless you tell it where to look. To tell Razor, add this to your web.config:

Refer to the Nancy documentation for a proper explanation of this.
Having added the web.config snippet you can go ahead and use Nancy.Linker to generate links in the Razor code:

That's all folks!

Sunday, July 27, 2014

Using Nancy.Linker with Views


You have two options: 
  • The simplest is to use Nancy.Linker in your route handler to generate the links needed in the views, put them on the view model and pass the view model to the view as usual. 
  • The other is to pass IResourceLinker to the view and allow it to generate links as needed. For this to work you may need a little bit of web.config'ing to make Razor play nice. 
This post shows the former.

Nothing New

In the last post I introduced Nancy.Linker, showed how to use it to create links to named routes and place them on a model object returned by a Nancy route handler.

In essence; given this module:

This route handler will return a model with a link to the route in the module above in either XML, JSON or whatever other format you have support for in your application:

(how the format is chosen, and which are supported is another story)
Now, if you want to show that link in a view, you just have to add one line the to handler and - of course - view code. The handler becomes:

Assuming you are using Razor for your views the bar.cshtml view can simply be:

There you have it. Just use Nancy.Linker the same as when returning data, point to the view from the handler and use the generated link as any other string passed to a view.

This is the approach I'd recommend, but in the next post I will show how to use IResourceLinker in Razor code.

Saturday, July 5, 2014



Nancy.Linker is a small library for creating URIs for named routes in Nancy application that I released to NuGet the other day.

Purpose of Nancy.Linker

The problem Nancy.Linker solves is to allow your application code to create URIs pointing to endpoints in your Nancy application without hardcoding the URI. Instead you refer to the endpoint by its route name and provide values for whatever route parameters the route expects. The library then returns you a suitable System.Uri.


Let's consider a Nancy application with this module in it:

The module does nothing interesting, but bear with me. The thing to notice is that FooModule has all sorts of routes - a constant one, one with a simple parameter, one with a constraint on a parameter, one with a regex segment with a captured parameter, one with an optional parameter and one with a default value for an optional parameter. To read up on Nancy routing check out the docs.

Now let's assume another module needs to put links to endpoints in FooModule in its own response. It can do so by taking a dependency on IResoureLinker from Nancy.Linker and asking it to create the URIs:

which will produce a response containing a bunch of links back to the FooModule. For instance the call 

results in this string (assuming your application runs on

Getting Started

Just install Nancy.Linker from NuGet:

Nancy.Linker will take care of registering the IResourceLinker with your container, so modules can just go ahead a take a dependency on IResourceLinker.

Monday, June 9, 2014

Software Architecture Open Space 2014

The fourth annual Software Architecture Open Space Conference is taking shape. The date is set to October 2nd. The registration has opened. The venue is booked. The announcements and invitations are being sent out.

This years conference will follow the lead of last years conference and be a 1-day event in Copenhagen. The day will be all about in-depth discussions, sharing knowledge, learning together and making connections.The team behind the conference is also the same as the team last year: Jeppe Cramon, Jakob Bendsen, Nikola Schou and myself.
The one thing changed compared to last year is that the price has gone up. The event is still non-profit - just as it has always been - but it turned out we lost money last year, so this year the price has gone up some in the hope that we hit the zero.

As has been the case all the three previous years the day is centered around around a series of Open Space sessions. The Open Space format allows attendees to shape the conference to be about exactly the subjects they want: Anybody can propose a subject and anybody can contribute to the discussion around that subject. More than that actually. Not only can attendees participate. They are expected to do so. They are expected to share the knowledge they have, to actively take part in discussions, and to propose subjects. This format has worked very well the previous years. I have personally learned a whole lot as well as grown my network substantially at previous Software Architecture Open Space Conferences.

Hope to see you there! Now go register :)

Saturday, May 31, 2014

Breaking Domain Layer Dependency on Data Layer: Use Events for Writes

In this final part of my series (part I, II and III) on reversing the dependency from Domain Model to Data Access code found in many traditional layered code bases I will show how raising Domain Events when Domain Objects are updated can further decouple the Data Access component from the other components.


To recap the initial situation is this:

The two previous posts show how to reverse the dependency between Domain Model and Data Acces either by letting the Presentation Layer talk to the Data Access code or by invoking Dependency Inversion.

Leaking Data Access Concerns?
Reversing the depedency by letting the Presentation component depend directly on the Data Access component works, but leaves the responsibility of making the Data Access component save entities to the Presentaion component. E.g. in this snippet of Presentation Layer code there is a call to wishListRepository.Save(wishList);

This may seem innocent enough, but saving is not a presentation concern, which means presentation code should not be making that .Save call.

Reversing the depedency by Dependency Inversion also works and alleviates the Presentation code from calling .Save. On the other hand the Domain Model code has to make the Data Access code save entitites. Doing this without the compile time dependency pointing from Domain Model to Data Acces is achieved by introducing interfaces like this in the Domain Model:

Again this seems innocent enough, but what about the Save method? On the one hand it does not reveal anything in particular about the underlying Data Access code or database. On the other hand it does imply that WishList objects can be saved - presumably to a database of some kind. Furthermore the Domain Model has to decide when to call .Save, which is not really a Domain Model concern. The Domain Model should be responsible for the Domain logic. The 'what' and the 'how' of persistence is the responsiblity of the Data Access component. The 'when' of persistence is also the responsibility of the Data Access component in simple cases and of Infrastructure code in more complicated cases.

Domain Events Enable Further Decoupling
If the Presentation component is not to call .Save and the Domain Model is not to call .Save then what? -The Domain Model will raise events when Domain Objects are updated - as done at line 10 in this:

The actual saving of the WishList is done in an event handler, which can be something along the lines of - notice that this class is part of the Data Access component and uses the Domain Model:

Now neither the Domain Model or the Presentation component makes any decisions about what, how or when to persist. The Presentation layer only retrieves Domain Objects as needed and interacts with them. The Domain Model just implements the Domain Logic and raises events whenever there are state changes. It is the full responsibility of the Data Access component to handle the 'what', 'how', and 'when' of persistence.

A Caveat
It is not always good enough to simply persist state changes right away as Domain Events are raised. Sometimes a Unit Of Work is needed. In such cases the Domain Event handlers should not persist data directly, but rather interact with the Unit Of Work to record changes. Whether the Unit Of Work eventually ends up being commited or not is not the concern of the Domain Event handlers. They can rely on Infrastructure code to take care of persisting or discarding the changes recorded by the Unit of Work.

Simple Eventing
Implementing a simple mechanism for raising and handling Domain Events amounts to iterating over all Subscribers calling them one after another when a Domain Event is raised, and to register all Subscribers. That is having this:

and registering all Subscribers with that class in the Composistion Root. This can be done by explicitly listing all subscribers, by discovering them by scanning assemblies or in case the application uses a IoC/DI Container by asking the Container to resolve Subscribers.

Rasing Domain Events further decouples the Data Access component from the rest of the components. It frees other components of the responsibility of deciding what and when to save, and it allows both for simply saving immediately and for delegating to a Unit of Work.
Raising Domain Events also allows for similar deploupling of other components - e.g. integrations to third parties.

Tuesday, May 13, 2014

Breaking Domain Layer Dependency on Data Layer: Dependency Inversion

This 3rd post in the series about moving from an architecture where Domain Model code depends on to Data Access code to an architecture where that dependency is reversed shows how that can be accomplished using Dependency Inversion.

To recap the situation we come from is this:

and we want to get to this:

While the dependency points from the Domain Model to the Data Access component we might have code like this in the Domain Model:

which depends on this interface in the Data Access Component:

Reversing the Dependency
Let's take a look at what the Dependency Inversion Principle as formulated by Uncle Bob tells us:

"Abstractions should not depend upon details. Details should depend upon abstractions"

This tells us that the Data Access code - a detailed level - should not depend on the Domain Model - an abstraction - but vice versa. In other words the Domain Model component should be changed to include this interface

which should be used by the Domain Model code:

That new DomainModel.WishListRepository interface should be defined in the Domain Model and implemented in the Data Access component:

And that inverts the dependency.

We have inverted the dependency between Domain Model and Data Access, such that the Data Access component now depends on the Domain Model, while the Domain Model has one dependency less.
As a side effect the type WishListDTO disappeared, so we end with less code and a better separation of concerns.

Tuesday, May 6, 2014

Breaking Domain Depedency on Data Access: Let Presentation Depend on Data Access

This is the second post about not letting domain layers be depend on data access layers. This post explores the (maybe) most obvious way to reverse the dependency between domain model and data access in classic three-layer architectures

Which is to basically turning this

into this

Notice that the arrow from the Data Access component to the Domain Model? Why is that there?
To answer that lets take a quick look at an example. Say we have a web enabled e-commerce system with an endpoint that lets clients add an item to a logged in users wishlist (in others words a simplistic version of something like Amazons wishlist). To do that the code for the endpoint needs to:
  • Get the user the call is made on behalf of
  • Retrieve that users wish list from the data access component
  • Add the item to the wish list
  • Save the updated wishlist back through the data access component
Which is accomplished with code along the lines of:

This code looks almost like it would have in a classic 3-Layer Architecture. So how does this code justify the dependency arrow from the Data Access component to the Domain component? It does so because:
  • The WishListRepository is found in the Data Access component
  • The call wishListRepository.GetByUserName(Context.CurrentUser.UserName)
    returns a Domain object - an instance of the WishList Domain class.
  • The call wishListRepository.Save(wishList) accepts a Domain object
So there you have it: Allowing the Presentation component to talk to the Data Access component allows you to cut the dependency from Domain to Data Access, but introduces the reverse dependency. For the reasons argued in the first post (and in the resources referenced there) this a much better position to be in than the one in the top most diagram.

An Added Benefit 
 Notice that the data access component now returns Domain objects when queried. That is possible because the dependency points from Data Access to Domain. It used to be the other way around. So ... what did the Data Acces code return on queries before? Most likely some object containing the relevant data from the data base. These types of object come under different names: WishLisDTO, WishListEntities (as in NHibernate or Entity Framework entity), DataModels etc. Regardless of the name their main purpose is to move data from the database into the layer on top of the Data Access layer (i.e. the Domain layer in the top most diagram). But now that the Data Access code returns Domain objects directly these are no longer needed to move data into the rest of the system. In the cases where the mapping from the database to objects is not complicated these DTOs/Entities/DataModels have become superfluous and can be deleted. This can turn out to be a lot of code that can be deleted.

The major downside here is that the endpoint code has been given slightly more responsibility, since it now has to fetch Domain objects - which it also did before - and also has to save them again after interacting with them. Depending on the state of affairs before breaking the Domain to Data Access dependency the endpoint may or may not have had to explicitly save changes. That may have been handled by a combination of dirty tracking and infrastructure code.
In the 4th post of this series I will show a way to remove this extra responsibility from the presentation layer again.

Monday, April 28, 2014

Domain Models Should Not Depend on Data Layers

This is the first of 4 posts about how to go about moving from an architecture where the Domain Model depends on the Data Acces component, to an architecture where that dependency is reversed.

In this post I outline the problem that I propose solutions for in the next posts.

Why Write About This?
Because I see this problem repeatedly in code that I get to work with. So I might as well write down what I tend to talk to clients about in those situations.

Why Do So Many Domain Models Depend on a Data Access Component?
I think there are several reasons, but the most important one it seems to me is that for many this seems to be the default for any server side software:

So that's how many systems start out. Or so it seems from my experience. At some point in the life time of the system the Business Logic component is repurposed as a Domain Model - this may happen is an attempt to get away from Transaction Scripts, or simply because having a Domain Model is seen as The Right Thing To Do (™).

Why Reverse the Dependency?
As long as the Domain Model depends on the Data Access component both are hampered. Albeit for different reasons.

Having the Domain Model depend on Data Access layer is a violation of the Dependency Inversion Principle because the Domain Model is a higher level of abstraction than the Data Access component. The consequence is that the Domain Model is tighter coupled to the details of Data Access than it should be leading the poorer maintainability and poorer testability. In fact Domain Models should be POCOs with no other dependencies than the standard library.

Having all other component depend - directly or indirectly - on the Data Access component, makes the Data Access code harder and more risky to change because it potentially effects everything else. The Data Access component is at the edge of the system and just like the entire system should not depend on the Prensentation component (another component at the edge) the entire system should not depend on the Data Access component.

Therefore this is preferable:

For deeper explainations of this I recommend Alistair Cockburns article on Hexagonal Architecture and the GOOS book by Nat Pryce and Steve Freeman.

How To Break the Dependency?
The upcoming posts covering these tactics for breaking the dependency:
  1. Allow presentation layer to talk to data layer
  2. Dependency Inversion
  3. Use domain events for writes
BTW. This applies to other stuff too. E.g. integration components or hardware access components.

Saturday, March 8, 2014

In Search of Maybe in C# - Part III

Following up on the last two posts[1, 2] this final post in my little series on Maybe/Option gives a third implementation of Option. This time around I'll drop the idea of letting Option implement IEnumerable and instead focus on implementing the function needed to make my Option a monad (which it wasn't actually in the last post).

First off let's reiterate the basic implementation of Option - a simple class that can be in two states 'Some' or 'None', where Options in 'Some' state contain a value and Option in 'None' state don't.

I also want to maintain the matching functionality that I had  in the other posts, so I'm keeping this:

While even this is somewhat useful as is, it becomes better if we add the remaining part of the monad; the FlatMap function (the unit function is the Some(T value) method, so only FlatMap aka Bind aka SelectMany is missing). So we add this to the OptionHelpers class:

This is nice because now we are once again able to chain operations without having to worry much about null ref exceptions.
Just for convenience I'll throw in a Filter function in the OptionHelpers as well:

To exemplify how Option can flow through a series of operations take a look at the following where there is a value,so the some case will flow through:

In the case of no value the none case will flow through as in this example:

Towards the end of the first post in the series I mentioned that it's nice to be able to treat Option as a collection. That led to Option implementing IEnumerable in the second post, thus enabling passing Options into existing code working on IEnumerables, which is quite useful when introducing Option into an existing code base. Especially so, if it's a code base that uses LINQ a lot. In such code you're likely to find functions accepting an IEnumerable and returning an IEnumerable. An Option type implementing IEnumerable fits rigth in. On the other hand, if you don't have exiting LINQ based code to fit into, the Option version in this post is maybe a bit simpler to work with because it has smaller API surface and it still provides the benefit of allowing chaining.

Thursday, February 20, 2014

In Search of Maybe in C# - Part II

In my last post I wrote that I'd like to have an implementation of the Maybe monad in C#, and I explored how to use the F# implementation - FSharpOption in C#.

In this post I'll show a quick implementation of Maybe in C#, I'll call it Option - as was noted in some of the comments on the last post this turns out to be quite simple. I left off last time mentioning that it's nice when Option can act somewhat as a collection. That turns out to be easy too. Just watch as I walk through it.

Implementing basic Option
First of all the Option type is a type that can either be Some or None. That is simply:

which allows for creating options like this:

So far so good. This all there is to a basic Maybe monad in C#.

Simulate pattern matching on Option
As argued in the last post I'd like be able to do something similar to pattern matching over my Option type. It's not going be nearly as strong as F#s or Scalas pattern matcing, but it's pretty easy to support these scenarios:

All that takes is adding to simple methods on the Option type that each check the value of the Option instance and calls the right callback. In other words just add these two methods to the Option class above:

That's matching sorted.

Act like a collection
Now I also want Option to be usable as though it was a collection. I want that in order to be able to write chains of linq transformations and then just pass Options through that. To illustrate, I want to able to do this:

This means that Option must now implement IEnumerable<T>, which is done like so:

And to be able to get back an option from a IEnumerable with 0 or 1 element:

which is useful in order to be able to do the matching from above.

All together
Putting it all together the Option type becomes:

Not too hard.

Wednesday, January 29, 2014

In Search of Maybe in C#

One of the things working in Scala has taught me about C# is that the maybe monad is nicer than null.

In case you're not sure what the maybe monad is: It's a generic type that either contains a value or not. In Scala as well as in F# this type is called Option and can be either Some - in which case it contains a value - or None - in which case it doesn't. This allows you to represent the absence of a value in an explicit way visible to the compiler, since Option<T> is a separate type from T. This turns out to be a whole lot stronger than relying on null to represent the absence of a value. I'll point you to an article about F#'s Option for more explanation on why.

Functional languages will usually let you pattern match over Option, making it very easy to clearly differentiate the case of Some from the case of None. In F# this look like so:

In C# we don't have this. The closest thing is Nullable<T>, but that doesn't work over reference types. But is Nullable<T> really the closest thing in C# to Option? - NO. As was pointed out to me in a recent email exchange the F# Option type is available in C# too.

Let's see if we can redo the above F# code in C#. First the declaration the name variable:

The F# Option type is part of the FSharp.Core assembly and the is actually called FSharpOption. Hence the line above.
On to the nameOrApology variable:

Not nearly as clear as the F# counterpart. What's in the if part; what's in the else part. Not nearly as clear to me as the pattern matching in F#.
We can do better, using this little helper extension function:

Which let's us initialize nameOrApology like this:

Now the two outcomes - a value inside the Option or no value - are much more clear to me.

This is OK. Although the name, FSharpOption, is not too nice. Some of the method names - e.g. get_IsSome - aren't nice either. More importantly: Another thing Scala taught me is that it's nice if Option can be used in place of a collection. But that's for another post.

Sunday, January 19, 2014

Slides from Warm Crocodile Talk

At the awesome Warm Crocodile Developers Conference I did a talk under the title "Does Your Architecture Enable Flow?". These are the slides from my talk. As always the slides make less sense without the words, so YMMV.