Friday, November 26, 2010

Slides from DCI talk at ANUG

I did a talk on DCI at my local .NET User Group, ANUG, the other night and had a great time. The slides from the talk were:




The slides were followed by three demos:

  1. A simple Scala example "cross"-compiled to run on .NET
  2. A simple Ruby example running on IronRuby
  3. A slightly larger ASP.NET MVC based C# example, which I will be posting details about in the furture.

Tuesday, November 16, 2010

Upcoming events

I just wanted to point to 2 events that are coming up soon that I am participating in:

  1. I am doing a talk on DCI in the Aarhus .NET User Group on the 24th of November 2010. Register at  http://on.fb.me/9QOa3s 
  2. I am participating in Random Hacks of Kindness during the weekend 4th and 5th of December 2010. More info and registration at: http://rhokaarhus.eventbrite.com/ 

Thursday, October 14, 2010

A Pinch of Functional in my C# - An Everyday Example

I'm working on a codebase that, like many other code bases,  has a number of data access objects(DAOs) that all inherit a common superclass. The other day I got tired of looking this pattern of code repeated a lot in the DAOs:
    1        public MyDTO GetMyDTO(...)
    2         {
    3             DataContext DB = NewDBContext;
    4             try
    5             {
    6                 DB.Connection.Open();
    7                 //Fetch something from the DB and return it
    8             }
    9             finally
   10             {
   11                 if (DB.Connection.State == ConnectionState.Open)
   12                     DB.Connection.Close();
   13             }
   14         }

I wanted the creation of the DBContext and the handling of the connection to be factored into somewhere reusable. So I applied the functional "suround with" pattern and introduced this method in the superclass:
    1        protected TReturn UsingDBConnection<TReturn>(Func<DataContext, TReturn> func)
    2         {
    3             DataContext DB = NewDBContext;
    4             try
    5             {
    6                 DB.Connection.Open();
    7                 return func(DB);
    8             }
    9             finally
   10             {
   11                 if (DB.Connection.State == ConnectionState.Open)
   12                     DB.Connection.Close();
   13             }
   14         }
and the DAO code then turns into this:
    1        public MyDTO GetMyDTO(...)
    2         {
    3             return UsingDBConnection(DB =>
    4             {
    7                 //Fetch something from the DB and return it
    7             });
    8         }

C# has supported this for years now, so why am I posting it? -Because I wish I saw more of this type of code. To me it's easy to read and I get to reuse the common part.