Andre de Cavaignac

Let's blog it out...

September 2007 - Posts

Strong Typed Functional Programming In C#

Functional Programming in C# Sample Solution (.NET 3.5)

I had an interesting discussion the other day with a collegue at Lab49 about the uses for functional programming over object-oriented programming.  Although I traditionally have been very OO-focused, some of the points he made are very relevant and things I have found myself doing in the past.  Although I have dabbled in some functional languages (PowerShell being the most prominent recently), I do not consider myself a functional programmer.

Typically, functional programming is loosely typed and uses dynamic languages, however functional programmers using an OO language (such as C#) will use hashtables or data sets to store loosely typed data.  The benefit of the loosely typed, "flat" object model (single object for all your data properties) is that you don't wind up creating excess code (such as properties that will never be filled in) for doing something very simple (like binding to a grid).  Furthemore, in an environment where new types are created daily, some of which will wreak havoc on your structured object model (which ultimately may never be used when you're just displaying data), the OO concepts can fall apart.  Take into account distributed computing and thread safety, and you have a very comelling reason to have a set of small flimsy objects that don't care what data they hold.

Running with this concept (which I still have yet to actually accept), I started to realize this is largely the direction of the C# language.  Extension methods, the var keyword, LINQ, and other recent developments in .NET 3.5 are all attempts to make a ridged OO language more dynamic.

Not wanting to lose my type-safety, I tried to go off an build a functional-style app using C#, and found an interesting way of using extension methods to apply "schemas" to loose typed hashtable data objects.  While this is not perfect, and I certainly would never use this in production code, it provides an interesting way to apply composite interfaces on top of an object without ever modifying the object itself.

 The use of extension methods is simple.  By creating GetProperty() and SetProperty() methods (where Property is the name of the property you wish to get set) as extension methods in a seperate namespace, you can easily use the namespace as an interface that you place "over" the data object.  You can write your functional method, import a few namespaces, and all of a sudden have a strong-typed interface for your functional method to access, cool stuff.

While I don't particularly condone this method of development (for if no other reason, other developers will have to wrestle with the code becuase its "not standard"), its worth looking at. 

Functional Programming in C# Sample Solution (.NET 3.5)

More Posts