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.

C# to Python

I was suppose to do a task which I could do it in any language and my obvious first choice which is purely due to comfort level is C#. I was set to do it in C# and while reading around one, I noticed one of the recommendation for the task is ‘language not limited to c, java or python’. This intrigued me to check out Python. I always heard lot of good things about Python so I spend an hour going through some basic language rules and semantics. At its core, it is very simple, so I decided to learn Python as a part of the process. Here are few things surprised me since I am coming from C# world.

Normally when you want to access an element in an array, we do it by array[index], which is straight forward. If you want to access the last element in c#, you would do this by array[array.Length – 1]. In Python, you can access it directly as array[-1], I thought it is very clever.

Python also have the for and while loop but what surprised me is the way of using ‘else’ in conjunction with loop. Lets say if you want to break from a loop, you will add a if condition inside the loop and break out. Now, if you want to check after loop if the loop exited normally then you add else at the end of the loop. Have a look at 4.4 in the this link.

This one is not a really surprise still worth mentioning. In C# we have value type and reference type. In Python everything is reference type, but they do have mutable and immutable. Like in C# string is still immutable and the collections like list and dictionary are mutable. On the other hand if you want to create an immutable collection ‘tuple’ will help you there.

The next two things are more to show the power of the language. You can write code as function programming model. You can mix and match between functional and oo style if you want. For example, you can create a function and then assign a variable with a value as parameter which in turn you can use it down the line. Take a look at this article, it explains very well.

The last one is so far the best; in Python it is called ‘List Comprehension’. The idea is very simple, if you want to create a new collection from a collection based on some simple if then else, then you can code the full condition in a single line of code. Take a look at the question answer in the stack overflow. I know we can do the same with simple Linq or lamba, but still it is pretty cool. This is something we use more often then you think.

I will keep you updated on anything new I learn or if you have comments or suggestions please let me know.

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.

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.

Collection Assertion in MSTest and Kata

I have been doing Prime Factor Kata with one of my friend. If you want to follow along, there is a great video post at Rickard Nilsson blog. For this Kata, my first attempt was to use C# (obviously), NUnit. All worked very well. So out of curiosity, I decided to change it a little bit, use MSTest. I was expecting the same code I wrote in NUnit would work in MSTest but to my surprise, even my first test failed. Here is my first test

Assert.AreEqual(1.Primes(), new List<int>());

Here is the Primes implementation

public static List<int> Primes(this int n)
{
   return new List<int>();
}

Very simple. In NUnit, when you assert a condition on a collection, it just does assertion, while in MSTest, you can not use Assert against a collection.If you need to do assert against a collection, you need to use CollectionAssert.AreEqual. So when I changed the code to CollectionAssert, it worked like a charm. But here is a catch though, if I had the code like

public static IList<int> Primes(this int n)

The assertion will not work since IList does not implement ICollection, rather it implements ICollection<T>. There are ways to work around that, but I found a better way of doing the whole thing anyway. If you want to do it like NUnit, then, what I would recommend is to install NBehave. Specifically the NBehave for .Net. With that installed, now the same test I used in the beginning of the blog would be like this and more readable.

1.Primes().ShouldBeEqualTo(new List<int>());

Which is more readable and the same code works with NUnit and MSTest. The whole benefit of Kata for me besides the obvious, I was able to compare little bit of MSTest and NUnit. Based on what I have done, I decided to use NUnit just for ‘Parameterized Test Fixtures’. One of the thing we do while doing the Kata is code, refactor. It turned out, all my tests were copy paste except the input and expected result.So rather than have eight separate tests now I have one consolidated test with the input and expected result been passed in as attribute to NUnit. Here is the final code

[TestCase(1, new int[0])]
[TestCase(2, new int[1] {2})]
[TestCase(3, new int[1] {3})]
[TestCase(4, new int[2] { 2, 2 })]
[TestCase(6, new int[2] { 2, 3 })]
[TestCase(8, new int[3] { 2, 2, 2 })]
[TestCase(9, new int[2] { 3, 3 })]
[TestCase(3*5*7*11, new int[4] {3,5,7,11})]
public void Should_Find_Primes(int t1, int[] t2)
{            
     Assert.AreEqual(t1.Primes(), t2);
}

Thats all about it, good way to start a new year by learning something new and cool.