0

Refactor code, Design Practices

by volkanuzun 10. November 2008 21:31

I start reading "More Effective C# from Bill Wagner". It is a really nice book, unlike the other books i read, with this book i start reading random chapters. Actually not that random, the chapters that i like more :) I will highly recommend this book btw.

So lets take a look at the Item 17: Create Composable APIs for Sequences

here is a simple code from the book:

public static void Unique(IEnumerable<int>num)
{
   Dictionary<int,int>uniqueVals = new Dictionary<int,int>();
   foreach(int num in nums)
   {
      if(!uniqueVals.ContainsKey(num))
         {
    uniqueVals.Add(num,num);
    Console.WriteLine(num);
         }
   }

 

 So what's wrong with the code above? First of all, the code is writing the unique numbers to the console on a passed IEnumerable<int>. However, the function is doing more than 1 principal job, it does 2 different things. First it loops through the numbers, collects the unique numbers in a dictionary, and second, it writes the numbers to the console. Because of 2 unrelated jobs being assigned to this function, it is not easy to reuse the code, and also not easy to  unit test the code. If you could seperate this 2 jobs into 2 different functions, it will be easier to unit test this code and also reuse this code. Let's try to do refactor code as step 1 progress:


public static Dictionary<int,int> Unique(IEnumerable<int>num)
{
   Dictionary<int,int>uniqueVals = new Dictionary<int,int>();
   foreach(int num in nums)
   {
      if(!uniqueVals.ContainsKey(num))
         {
    uniqueVals.Add(num,num);
 }
   }
   return uniqueVals;


private static void PrintUniques(IEnumerable<int>numbers)
{
      Dictionary<int,int>uniqueVals = Unique(numbers);
      foreach(int num in uniqueVals )
      {
         Console.WriteLine(num);
      }

 

Now we divided the function into 2  functions, and they can be easily reused as they only do 1 task, also it is easier to unit test it (to unit test PrintUniques function, you can use StreamWriter instead of console). However we can easily refactor this code more :), using "yield". Yield is an interesting function, it returns the value while you are iterating one at a time. One big advantage is you dont have to load the whole array into the memory, so if in any part of your loop, you have an exit from the iteration, you wont end up having everything loaded in the memory and not using it :) So you will get the value, and the index pointer will move to the next element, for the next step in the iteration. This is kinda like lazy loading in LINQ. Here is the code again:

 

public static IEnumerable<int> Unique(IEnumerable<int>num)
{
   Dictionary<int,int>uniqueVals = new Dictionary<int,int>();
   foreach(int num in nums)
   {
      if(!uniqueVals.ContainsKey(num))
         {
    uniqueVals.Add(num,num);
            yield return num;
 }
   }


private static void PrintUniques(IEnumerable<int>numbers)
{
      foreach(int num in Unique(numbers))
      {
         Console.WriteLine(num);
      }

 

 Hope it is clear and easy to understand. Let me know if you have any questions. 

Tags: ,

0

const vs readonly

by volkanuzun 3. November 2008 08:36

Probably you already know that, const variable must be assigned a value when they are defined, however readonly values can be assigned a value during the construction time,after they are declared. Is there any other differences we should know? Well, let's look at a simple class:

 public class constref
    {
        public const int MagicNumber = 5;
        public readonly int MagicNumber2 = 10;
    } 

 

I declared a simple class, that has 2 public members, a const and a readonly, after i compile this, and using ildasm i look at dll file. Here is what i got for the constant value MagicNumber:


.field public static literal int32 MagicNumber = int32(0x00000005)
 

The variable is converted into a static int32 and its value is assigned right away. This means, if any other dll is referencing this dll,  when they dereference MagicNumber, at the compile time, the value of MagicNumber will be replaced to that library. Example: Assembly B is referencing the MagicNumber variable inside this constref class, and in the code it has something like: constref.MagicNumber => this will be replaced with 5 during compilation.  Which also means, if you change the constref code, and set the const value to 8, and dont compile Assembly B, assembly B will still have 5 (the old value).

Let's look at the readonly variable after compile: 


//this is the decleration:
.field public initonly int32 MagicNumber2

//this is the constructor created by compiler:
 .method public hidebysig specialname rtspecialname 
       instance void  .ctor() cil managed
{
  // Code size       16 (0x10)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldc.i4.s   10
  IL_0003:  stfld      int32 constvsreadonly.constref::MagicNumber2
  IL_0008:  ldarg.0
  IL_0009:  call       instance void [mscorlib]System.Object::.ctor()
  IL_000e:  nop
  IL_000f:  ret
} // end of method constref::.ctor

 

This time, the value isnt assigned at the declare time (even though that is what we did), but it is assigned at the constructor. One big advantage is that, if we apply the same scenario, Assembly  B derefencing the value of MagicNumber2, will be using runtime values. So we change the source for constref class, and assign 20 to MagicNumber2, and just recompile constref, we dont have to compile Assembly B to reflect the new changed

Tags: ,

0

Resharper is GREAT

by volkanuzun 21. March 2008 17:42

Since i installed resharper ( few days ago ), i enjoy using vs 2008 more. Not only it helps me to write fast code, it also teaches me better coding :)

You wonder how ? When i have a data representing class, i always overload ==,!=, Equals, GetHashCode() functions, such as:

    public override string ToString()
        {
            return Name;
        }
        public override int GetHashCode()
        {
            return Name.GetHashCode();
        }
        public override bool Equals(object obj)
        {
            if(obj == null)
                return false;
            Branch temp = (Branch) obj;
            return temp.Name.ToLowerInvariant().Equals(this.Name.ToLowerInvariant());
        }

        public static bool operator==(Branch d1, Branch d2)
        {
            object o1 = (object) d1;
            object o2 = (object) d2;
            if( (o1== null) ||(o2==null))
                return false;

            return d1.Equals(d2);
        }

        public static bool operator !=(Branch d1, Branch d2)
        {
            return !(d1 == d2);
        }

 

Today while i was doing the same thing for another class, right before i was going to overload, resharper's yellow icon poped up, i hit insert enter, and resharper asked me if i want to overload members, i click sure go ahead, here is the resharper code which is a lot smarter than mine:

public bool Equals(Counselor counselor)
        {
            if (counselor == null) return false;
            return Equals(Email, counselor.Email);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(this, obj)) return true;
            return Equals(obj as Counselor);
        }

        public override int GetHashCode()
        {
            return Email != null ? Email.GetHashCode() : 0;
        }

 

 

Tags: ,

Powered by BlogEngine.NET 1.6.0.0
Original Design by Laptop Geek, Adapted by onesoft