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

C# Best practices – String

Few things I want to point out when using string in C#.

In C# so as Java, string is immutable. what does it mean by immutable? immutable is that once an object have a value it never changes. For example, when you have a value ‘unni’ assigned to ‘name’ variable, and later if you decide to change the name ‘unni’ to say ‘nair’, then when you assign the value to ‘name’ variable, it creates new memory and put the value ‘nair’ in it and point to that location. The important point in here is that, the value ‘unni’ never got overwritten. That memory location now becomes garbage for garbage collector to pick it up. So you have be very careful when using string, always mindful of its immutability so that you will not create too many garbage memory so fast. You can think of immutability like ‘const’ or ‘readonly’ keyword in C#. One of the main benefit most of developers do not know is that immutability is that it naturally lend it self to concurrent programming.

Now that we know what is immutability, where could this cause problems for the novice programmers; Lets take the following code.

            string concatinatedString = string.Empty;
            for (int i = 0; i < 10; i++)
                concatinatedString += i.ToString();

This code does not look harmful. But if we go back to the example with my name what really happening is, the look is going to create 10 instance of the string variable each one with its previous string + current value.So when the program runs, you can see, it created 10 memory objects even though expected task was to append all numbers to the same variable.

image 

Now the question is, but I want to create a concatenated string so how do I go about doing it? The answer is very simple, use StringBuilder. By definition, this is mutable string of characters. So if any point you want to create mutable strings, try to use string builder. So the above code if we would use StringBuilder, it will be like the following

            StringBuilder concatinatedString = new StringBuilder();
            for (int i = 0; i < 10; i++)
                concatinatedString.Append(i.ToString());

Even though we have lot more memory to work with compared to old days, we should take every possible step to write an efficient code.

Some interesting things I learned over last month

This is a lazy blog 🙂 I have been very busy lately and learned a lot along the way as well. I wanted to write some blogs about parallel programming and Lazy loading, but time constrains still I am unable to do it. Rather than waiting long for me to write, I thought I post couple of links I used to learn and use them in the projects.

Lazy Loading:

In most of the cases, when you are doing lot of lazy loading, you will end up writing code which checks for null or default value and if it is in its initial state then you perform actual load. In C# 4.0, now we have some thing called Lazy<T> which help resolve this repetition. But if you would use it, then extracting value is little different than just calling the property getter. Rather than using property getter, you would use .Value to get the value.

Concurrent Collection items:

My current project is using parallel programming model, using PTL and PLinq. That by itself is a different blog, but if you are using any kind of parallel programming, you have to double check on how are you using the collections. Please do not use traditional collection if the data source is used across all threads. Instead use the concurrent collections specified in the System.Collection.Concurrent name space.

How to create code snippets using Snippet Designer?

I am working with my friend on creating a demo to show TDD. The whole demo took more than 30 minute, we were asked to reduce the time. When we write tests, we tend to write method names as long as possible so that when someone reads it, the name make perfect sense. So one thing I noticed, I spend most of the time typing large method names. One suggestion was not to type rather paste them and explain what the test does. Which led to the question, why not we use snippets? A good excuse for blog.

To start with go to snippet designer codeplex page and download the snippet designer. There is another way you can do it by creating XML etc., I like snippet designer very much and once you start using it, you may not go to XML format. Once it is installed, when you right click on the code, you should see an option to Export as Snippet

image

Select the option and export a snippet, it will open up a tab with the content you selected like the following

image

Two points are important here. Make sure you name the snippet (green circle) and then give name for shortcut (black circle). This is the name you are going to use to bring the snippet when you are in a code. Now save this file. There are two places you can save the snippet, one place is default visual studio snippet area. I will not save my snippet in there since it is specific to a project. If you are creating a snippet that you want to use a whole a lot, then you put it in Visual Studio directory. In my case I put it in the solution folder itself.  By default, snippet manager will show all the snippets stored in default visual studio directory so you need to tell snippet manager to look it up not only in visual studio default directory but also additional directories. To do that, go to tools –> snippet manager like the following

image

When you choose code snippet manager, it will show a dialog like the following

image

Change the language to C# and select Visual C# and select add to add the directory where you placed your snippets. Now that all pieces in place, go to your program and start typing ‘finalkata’ (Remember, this is the short cut name we gave?), as you type the intellisense should find your snippet and show up.

image

select it and double tab and bring the code. That’s about it. Very simple and easy to use. What I did not show is how to create the replaceable content inside the snippet, for what I did, it was not required. When I come around to use it, I will do another blog.

Missing Assembly even though it is in the same project

Yesterday I ran into a very interesting problem. I have a solution with three projects. When I compile, I get an error saying namespace not found or might be missing assembly. The error was pointing one of the project in the same solution. So I ended up building each project by itself and two projects compiled properly but the one kept failing with the same error.  Initially I thought, something might have messed up in the project dependencies and it turned out, that is not the case.

After looking at the properties of each project I found the real culprit. It is the target system in properties. So if you run into a problem, make sure Target Frame of all projects pointing to same type. In my case the failing one was pointing to .Net Framework 4 Client for some reason.

image

Hope this saves someone’s valuable development time.

My First look at Kinect SDK

It is not really first look, there have been people hacking Kinect the day, it was launched. If you have not seen the hacks, go to You tube and search Kinect hacks. They bunch of videos on it. Last weekend I attended Kinect for Developers @ Plano, TX. Shawn and gang did excellent job in organizing the event. The speakers were good. The best part was lab. Anyway, if any of you want to learn, head to Microsoft page to download. Hold on the thought on downloading, If you are coming in for the first time, I would recommend wait till February 1st to download the SDK. On Feb 1st, Microsoft is releasing a new version of Kinect and new SDK to go with it. So I would strongly recommend wait and download and start cooking.

I was really impressed with what I have seen and what I was able to accomplish in two days time. In my opinion, if you know XNA and if you are a game developer, you have a great head start since it is easy to add the gestures logic to the code and get input from the there and your code stays the same. If you are XNA developer make sure you go to app hub link.Also if you are a WPF/Silverlight Developer you also have head start. The interesting thing is, Kinect provides another medium of input and there are libraries available that you can use or extend to solve most of the common problems.

I have not decided to buy the Kinect that will be coming out on February 1st yet. I was told there will face reorganization and identify the figures. I think that will change the way we play games.

Passing TYPE around in C# (Generics)

Yesterday when I was doing a code review for one of my co-worker, I saw a scenario where there were two methods, where both the method does the same thing except for each one different types. It is a silverlight code, where he need to find a grid and another child element. By looking at the code, it begs refactoring, he was able to refactor the code easily with generics. When we did the refactor, I was wondering if there is another way of doing it without generics and it is. So here are the two ways to pass the types around and perform your check in a common function.

For our discussion we are going to have a heterogeneous collection, where we will an element of String, int, float and a List of int, like the following

genericList.Add("Unni");
genericList.Add(10);
genericList.Add(99.99);
List<int> tempList = new List<int>() { 2, 3 };
genericList.Add(tempList);

next we are going to write a method which will accept a TYPE as input and check if the type exists in the collection. The first and simple approach is by  passing the type itself as a parameter as shown below

public object CheckType(Type type)
{
    foreach (var t in genericList)
    {
        if (type.IsInstanceOfType(t))
            return t;
    }
    return -99;
}

Here is the associated test for his method

[Test]
public void It_Can_Return_10_When_int()
{
    Class1 c1 = new Class1();
    Assert.AreEqual(10, c1.CheckType(typeof(int)));
}

We walk though the collection and check each element is instance of a required type we need to find. If we find it, it will return the element from the collection. Now lets look at the second option using generics as it is supposed to be written

public object CheckType<T>()
{
    foreach (var t in genericList)
    {
        if (t is T)
            return t;
    }
    return -99;
}

and associated Tests

[Test]
public void It_Can_Return_10_When_int_As_T()
{
    Class1 c1 = new Class1();
    Assert.AreEqual("Unni", c1.CheckType<string>());
}

[Test]
public void It_Can_Return_List_When_List()
{
    Class1 c1 = new Class1();
    List<int> tempList = new List<int>() { 2, 3 };
    Assert.AreEqual(tempList, c1.CheckType<List<int>>());
}

We create a method and pass generic type T. Now the code which this is very elegant because you do not pass the type as the input parameter.