Refactor C# code using Action<T> or Func

Currently we are using Sonar to identify the health of our application. One of the code metric it gives is duplicate code. I was going through the code along with one of my colleague and found out that most of the code can be easily refactored except some complicated one.  We ran into a scenario where everything is same except some where in the middle the block of code is different. We were debating to split the common code in separate methods or use some strategy pattern to solve it. But then I remembered about C#’s nifty Action<T> and Func. So in this case, we refactored the whole method into a common method, except the small code block nested inside the code as an Action<T> and pass it to the common method.

Here is a very simple example on how to use Action<T>; we have two action methods, one (line 5 – 9) will display numbers from 0 to x, where x is the parameter passed in and the second (line 11 – 14) just display the number passed it

 

1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Action<int> singleLoop = new Action<int>(p => 6 { 7 for (int i = 0; i < p; i++) 8 Console.WriteLine(i); 9 }); 10 11 Action<int> singleWrite = new Action<int>(p => 12 { 13 Console.WriteLine(p); 14 }); 15 16 PrintValue(singleLoop, 10); 17 PrintValue(singleWrite, 5); 18 Console.ReadKey(); 19 } 20 21 private static void PrintValue(Action<int> singleLoop, int param) 22 { 23 Console.WriteLine("starting"); 24 singleLoop.Invoke(param); 25 Console.WriteLine("ending"); 26 } 27 } 28

As you can see from this example, you can inject the code snippet inside the code block based on which every logic you feel warranted. Func behave the same way, except, Action takes parameters but does not return a value back, on the other hand, Func returns a value.

Hope this helps someone.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s