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.