Sunday, August 4, 2013

Testing private methods/functions using VSTS unit test with c#

In case you are new to VSTS unit testing, you can read my article from codeproject.com:- 12 FAQ’s on VSTS unit testing.

Before you make an opinion about me and this article let me admit I am a strong opponent of unit testing private methods. For me a “UNIT” in unit testing means the “Class” as a whole. So if I test public methods of the class the private methods get tested as well.

It’s like should we test the wall or should we test individual bricks of the wall. Logically if the wall stands then the bricks are doing good as well.

But then there is a saying:-




So we have some other school of thought who think “UNIT” can be lines of code and methods. So they think that if you are testing private methods it’s ok and ethically right. And also many times you are in some weird situation like you are trying to zero on the method where the defect is ? , private testing seems to be a reasonable solution.

So with due respect to the second school of thought this blog will discuss how we can test private functions /method using VSTS test.

For example below is a simple “Maths” class which has an “Add” function. This “Add” function does not allow negative numbers. So to check if the number is negative there is a simple private function called as “IsNegative”. So how do we test “IsNegative”  through VSTS unit test framework?.

public class Maths
{
        public int Add(int num1, int num2)
        {
            if(IsNegative(num1) && IsNegative(num2))
            {
                throw new Exception("Number should not be negative");
            }
            return num1 + num2;
        }

        private bool IsNegative(int num)
        {
            if (num > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

In order to invoke private methods in VSTS unit test we have a class called as “privateobject”. Create the object of “PrivateObject” class and pass the class whose private method needs to be invoked. You can then use the “PrivateObject” object to invoke the private methods / functions as shown in the below code.

PrivateObject o = new PrivateObject(typeof(Maths));
bool b = Convert.ToBoolean(o.Invoke("IsNegative", -1));

FYI internally “PrivateObject” uses reflection to invoke the private members.

As said previously, unit testing private methods means there is seriously something wrong in the class design. This is also a sign that the class is overloaded with lot of responsibility and is not following SRP ( single responsibility responsible ). 

In this case the “Maths” class should only be doing arithmetic operations (Add, Subtract etc), but it is also loaded with responsibility of doing validation. So probably it’s a good idea to move the validation to a separate class called as “Validator” who will do the numeric checks and then use this class inside the “Maths” class.

You can then write test cases on the “Validator” class separately which is a cleaner approach than the previous approach of using “PrivateObject” and invoking them via reflection.

public class Validator
    {
        private bool IsNegative(int num)
        {
            if (num > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

Below is a simple video I have created which shows how to use “PrivateObject” class to invoke the private methods.

Saturday, July 27, 2013

C# interview question with answers :- What is Fragile parent class problem in c# ?

Inheritance is a great power by which developers can increase reusability in parent-child relationship. But with great powers comes greater responsibility and also problems. One of the problems which creep’s in is the “Fragile parent class problem”.


Take a simple scenario (below is the image) where we have a simple parent child class relationship. Assume that this child class is used in lot of projects and installed in lot of places. Now assume after the child class has been deployed across locations, after some months there are some changes in the parent class.

These changes can have cascading and unexpected behavior in child class as well. This unexpected behavior on child classes is termed as “Fragile class problem”.


Consider the below scenario where we have a parent class called as “DbParent” with a virtual method “Insert”.

class DbParent
{
     
        public virtual void Insert()
        {
            Console.WriteLine("Parent insert");
        }

}

Below is a simple child class with his own “Insert” implementation which is installed across various locations.

class DbChildClass : DbParent
{
       public void  Insert()
        {
            Console.WriteLine("Child inserts");
        }
}

Now let’s say after some months of deployment parent class developers without understanding the impact on child classes go and add a new method “Add”. This “Add” method calls the “Insert” method internally (below is the code snippet for the same).

class DbParent
{
public  void Add() // Adds method with out consulting
{
      this.Insert();
}

public virtual void Insert()
{
            Console.WriteLine("Parent insert");
}
}

Now client programs who invoke the “Add” method by creating child class objects expect that the “Child” class “Insert” implementation should be called.

DbChildClass o = new DbChildClass();
o.Add();
Console.Read();

But whoaaaa, if you run the below code you will see the parent class “Insert” is called which is not EXPECTED.









So the next question is what is the proper way of solving this issue?. First thing to my understanding (I can be wrong) there are no standard and common ways of solving the problem.

One of the thought which goes here is, if the base class is very fragile (will change time to time) then inheritance should not be allowed further. So by marking the classes as “sealed” or the fragile method as “sealed” this problem can be controlled.

Second way would be avoid calling virtual methods in the parent class in other methods.

I am myself hunting for proper standard solutions so if you have some better suggestions, please do write down the same in the comments below.

Also I would like to point out that .NET framework handles fragile parent class issues to a certain extent by itself.  For instance in the below code even though the child class method “HandleNumerics” has been passed an integer value, it is still invoking the “HandleNumerics” with double data type.

So the framework assumes that the child class method should be given preference rather than parent class.

class Parent
    {
        public virtual void HandleNumerics(int d)
        {
            Console.WriteLine("Parent numeric ");
        }

    }

    class child : Parent
    {

        public  void  HandleNumerics(double d)
        {
            Console.WriteLine("Child numeric");
        }
        
    }

    class Client
    {

        public static void Main()
        {
            child o = new child();
            int i = 100;
            o.HandleNumerics(i);
        }
    }

The above code will display “Child Numeric” rather than displaying “Parent Numeric”.

Below is a simple youtube video which demonstrates the above auto fragile handling methodology by .NET framework. Many c# developers think that this is a defect but it’s actually done “By DESIGN” to solve the “Fragile base class” problem.
  




Sunday, July 21, 2013

.NET interview questions with answers: - Build solution VS Rebuild solution VS Clean solution

I am not aware of a single day in my life when I have not clicked on “Build”, “Rebuild” or “Clean” menu of visual studio. Even though I use it on a daily basis  or sometimes even minute to minute basis when my keyboard was high on coding, I was still not clear what exactly each one of these menus do.  I had very vague idea, but I wanted to be sure about the exact differences between them.

When I hunted the differences what came out was surprising, below goes a detailed explanation of the same.


Build solution menu: - This will perform an incremental build. In other words it will only build code files which have changed. If they have not changed those files will not touched.

Rebuild solution menu: - This will delete all current compiled files (i.e. exe and dll’s) and will build everything from scratch, irrespective if there is code change in the file or not.


Clean solution menu: - This menu will delete all compiled files (i.e. EXE’s and DLL’s) from “bin” / “obj” directory.

Now if you read the above 3 points I have discussed you can conclude that:-

Rebuild = Clean + Build

So the next question would be If you do a “Rebuild” and if you do “Clean” + “Build” , what is the difference ?.

The difference is the way the build and clean sequence happens for every project. Let’s say if your solution has two projects “proj1” and “proj2”. If you do a rebuild it will take “proj1” , clean ( delete) the  compiled files for “proj1” and build it. After that it will take the second project “proj2” , clean compiled files for “proj2” and compile “proj2”.

But if you do a “clean” and build”. It will first delete all compiled files for “proj1” and “proj2” and then it will build “proj1” first followed by “proj2”.

Below image explains the same in a more visual format.


















Below is a simple youtube video which demonstrates difference between these entities.



Big thanks to questpond.com to provide these c# and .NET interview questions with answers videos.






Saturday, July 13, 2013

C# and .NET interview questions with answers: - How can we mark a method as deprecated?

This question is taken from the book .NET interview questions written by Shivprasad Koirala.

Many times you want to warn developers that some methods or classes should not be used as they are either replaced or going to be replaced with new versions. This is possible by using the “[Obsolete]” attribute.

In the below class we have a method called as “Method1”. Now let’s say you have created a better improvised version of “Method1” called as “NewMethod1”. You want to send an alert to all your developers who are consuming this class to use “NewMethod1” rather than using “Method1”.

So you can decorate “Method1” with the “[Obsolete]” attribute as shown in the below code.

public class Class1
{
        [Obsolete]
        public void Method1()
        {

        }

        public void NewMethod1()
        {
        }
}

Now if any programmer consumes the above class he will get a warning message as shown in the below figure.













In case you want to show some message to the developers you can pass the message in the “Obsolete” attribute as shown in the below code snippet.

[Obsolete("Please use NewMethod1")]
public void Method1()
{

}

If you want to be bit strict and do not developers to use that method, you can pass ‘true” to the “Obsolete” attribute as shown in the below code.

[Obsolete("Please use NewMethod1",true)]
public void Method1()
{

}

Now in case developers try to make a call to “Method1”   they will get error and not just a simple warning.













Also visit our site from more such c# interview question with answers videos.

Also read this interesting .NET interview question with answer: - What is TPL ( Task parallel library ) ?





   

Thursday, July 4, 2013

C# circular dependency interview questions with answers.

Can you define circular dependency?

Circular dependency is a situation where “classlibrary1” references “classlibrary2” and “classlibrary2” is trying to reference “classlibrary1”.


If you ever try to reference class libraries with each other visual studio throws the below exception.


Can you explain a scenario where circular dependency situation occurs?

Consider a situation of a 3 layer architecture where the middle layer is consuming data access layer. Below is a simple “Customer” class which belongs to the middle layer and its making call to the data access layer using the “CustomerDal” class.

For now assume that both these classes are in different c# project.

    public class Customer : ICustomer
    {
        public int CustomerCode { get; set; }
        public string CustomerName { get; set; }
     
        public void Add()
        {
            CustomerDal oDal = new CustomerDal();
            oDal.Add(this.CustomerCode,
                             this.CustomerName);
        }
    }

public class CustomerDal
    {
        public void Add(int CustomerCode,
                        string CustomerName)
        {
         
            // database insert code goes over here
        }
    }

Now if you see the “CustomerDal” class the add method has data passed in variables. It would be great if we can pass the “Customer” object directly. In other words we are looking at a modified version of “CustomerDal” as shown below.In order to achieve the same “CustomerDal” project needs to reference the “Customer” project.

public class CustomerDal
    {
        public void Add(Customer cust)
        {
            
            // database insert code goes over here
        }
    }


Now already the “Customer” project is referencing the “CustomerDal” project and if you try to reference the “Customer” project in “CustomerDal” project, it would throw a circular dependency error as shown below.


How can we overcome the circular dependency problem?

Circular dependency problem can be overcome by using interfaces or events. So for the above problem we can introduce an interface in between the “MiddleTier” and “Dal”


So below is the solution. You can create an altogether different c# project and create an interface “ICustomer” as shown in the below code.

public interface ICustomer
    {
        int CustomerCode { get; set; }
        string CustomerName { get; set; }
    }
This interface project you will implement in the middle layer project on the  “Customer” class.

public class Customer : ICustomer
    {
        public int CustomerCode { get; set; }
        public string CustomerName { get; set; }
        
        public void Add()
        {
            CustomerDal oDal = new CustomerDal();
            oDal.Add(this); // passing the object ( polymorphism)
        }

      
    }
Now in the data access layer project you can reference the interface project and use the interface rather than passing the individual variables in the method.  When the middle layer makes a call to data access layer he will pass “this”. Due to polymorphism the customer object would be automatically type casted to the data access layer in the interface format. Please see the code of “Customer” class where in the “Add” method we have passed “this” object.

public class CustomerDal
    {
        public void Add(ICustomer cust)
        {
            
            // database insert code goes over here
        }
    }

Note: - Circular dependency is a sign of bad design and tight coupling. So when you get in to a circular dependency situation rather than fixing it directly by interfaces or events, question yourself why you landed in this situation.

Tuesday, June 11, 2013

Will US immigration bill kill Indian IT companies?

Contents

It’s all about jobs so it is

Gang of Four to Gang of Eight

Vocabulary used in this article

Point 1:- Increased visa Quota

Point 2:- Increase in VISA cost

Point 3:- Client side restriction

Point 4:- H1 B mandated salaries

Point 5:- Visa restriction in 3 phases

Impact on Indian IT overall


It’s all about jobs so it is… 

I really understand how sentimental this topic is for some US people who have a different feeling for outsourcing and immigration policies. Personally I respect the sentiment because it’s a very natural thing which any human would do. But my intention through this article is to not spark a debate if outsourcing is good or bad ?, did Americans loose jobs ? etc. My main intention here is to understand the technical points surrounding the new proposed US 2013 immigration bill and how it impacts Indian IT companies.

So please do refrain from making comments which would divert the cause of this article. Let peace and better understanding prevailJ.


Gang of Four to Gang of Eight












If you are one of those Indian developers whose interest revolves around programming, SQL, design patterns, it’s time to momentarily shift your attention from Gang of four (GOF) design patterns to Gang of eight (GOE) proposed immigration reform bill. Because this bill will affect Indian IT companies and directly to you to a great extent.

Now I am personally not sure if the bill will pass through. Until this date this bill is still debated in the senate. So incase for political reason this bill does not go through, this write up will go obsolete. 


It’s an 800 page long bill which makes it quiet complicated to understand. Especially if you are not residing in US then understanding the bill makes it more difficult. So the main purpose of this article is to make Indian developers understand what the bill says and what are the key points that will affect Indian IT companies. So below are 5 key points which I have extracted from the bill which concerns Indian IT.


Vocabulary used in this article

I am assuming that this article will generate more interest with in Indian developers than anywhere else. So I am going to use some vocabularies in this article which can be confusing at times for Indian audience. Some of these vocabularies would look very lame for people who are residing in US but I can bet many Indian developers are not aware of the same. Below is a short explanation of the same to avoid confusion.

Democrat and republicans: - These two are largest political parties in US like how we have BJP and Congress parties in India.

Gang of Eight:- They are bipartisan gang comprising of 8 people. Bipartsian means the gang comprises four people from democrat party and four people from Republican Party.  Please refer democrats and republican from the previous definition.
















US immigration bill 2013:- It’s a reform bill which is made in consensus by gang of eight to define a path for undocumented immigrants , improved visa system , fast tracking permanent residence in US  etc.

Indian MNC and US MNC: - In my whole article whenever I say “US MNC” I am referring to software companies which have been established and originated from US (ex. Microsoft, Apple etc). When I refer the word “Indian MNC” these software organizations are established and have origin from India (ex. Infosys, TCS etc).

Client side recruitment: - Software companies execute project in two ways in-house or at the client side. In house means they have their own premise and they develop project taking requirements from the client side. Client side means developers sit at client premises and execute projects.

As said previously the bill is an 800 page document which talks about various things like bringing undocumented (illegal) population in to a legal framework, green card, citizenship etc.  But for Indian IT industry the most important thing is impact on H1 and L1 visas. This is what Indian IT companies thrive on.  So my main focus of this article will revolve around how the bill impacts H1 and L1 statuses.

















Point 1:- Increased visa Quota

First let’s start with some good news. The H-1B visa quota would be increased from 65,000 to 110,000 and can be further increased to 180,000 depending on further demand. But this quota increase would benefit US MNC’s more rather than Indian MNC.  We will discuss about the same in the coming points.

Point 2:- Increase in VISA cost 

This is a definite impact on Indian IT companies. If you are not a US MNC and your IT work force is greater than 50 members:-
  • You need to pay $5000 more if you are filing more than 30% and less than 50% H1-B visa of your total IT work force.
  • You need to pay $10000 more if you are filing more than 50% H1-B visa of your total IT work force.

For US MNC’s the visa cost will be around $500 for every H1-B they recruit.

Point 3:- Client side restriction

This is a real killer for IT companies. If you are Indian MNC with employees in US comprising more than 15% H1-B of your total US work force, you cannot place employees directly on client side. Client side means your employees can not work in clients premises. Most of the Indian IT companies feed on this. Personally I feel 15% is a very less number. This clearly benefits US MNC as they do not have any restrictions.

Point 4:- H1 B mandated salaries

I personally like this point a lot. Indian MNC’s have been paying down rated salaries to Indian H1-B professionals in US. Due to this US MNC’s were not able to compete with them and second a local US developer had to compete with the down rated salaries. So now if this bill passes there will be strict H1-B mandated salaries. So this is a good news on a individual level, but for Indian MNC’s its taking their profit pie out and loosing edge over competitive rates with US MNC’s.

Point 5:- Visa restriction in 3 phases

In point 1 I talked about good news that there is increase in visa quota. But this increase in visa quota will not help out individual Indian MNC’s. It will help Indian IT overall but not individual MNC’s.

There is a 3 phase visa restriction which has been planned and it is as follows:-
  • From the year 2014 you can only apply for 75% H1-B’s of your total workforce. 
  • In 2015 only 65%.
  • In 2016 only 50%.

Impact on Indian IT overall

Looking at the points above the overall conclusion points are as follows:-

  • This bill definitely looks bad for Indian IT MNC’s but the bill is not bad for Indian IT Industry as such. Indian developers who are working in US will now get revised higher salary rates. 
  • Second the increase in visa quota means more people can now get jobs in US. Only the change will be you will not see people going from only selected Indian IT companies but will be spread across other Indian IT companies.
  • Clearly this will impact Indian IT MNC’s in the coming years due to increased visa fees, less allocated visa quota per MNC and client side placement policies. The bill favors more US MNC’s and they will definitely gain from the same.
  • Indian IT companies need to recruit more people locally and than sending onsite. So with this bill Indian companies will do lot of recruitment in Indian soil rather than US so that they do not get in to visa complications. 
  • Also probably the outcome of this bill will lead to better salaries in US MNC’s rather than Indian MNC’s. So in 2016 we should see Indian developers more attracted to US MNC’s in India rather than Indian IT companies.

I am not an expert in these kind topics. I am more of a technical person who does training on www.questpond.com . But because this topic interested me, so I thought of penning it down. So if you think if I have written anything wrong here or objectionable, let me know I will try to amend the same.










Sunday, May 12, 2013

Dependency injection (DI) VS Inversion of Control (IOC)

The main goal of Inversion of control and Dependency injection is to remove dependencies of a application. This makes the system more decoupled and maintainable.

First let’s try to understand IOC (Inversion of control).  If you go back to old computer programming days, program flow used to run in its own control.  For instance let’s consider a simple chat application flow as shown in the below flow diagram.
  1. End user sends chat message.
  2. Application waits for the message from the other end.
  3. If no message is found it goes to Step 2 or else moves to Step 4.
  4. Displays the message.
  5. User continues with his work ahead.

Now if you analyze the program flow closely, it’s sequential. The program is in control of himself. Inversion of control means the program delegates control to someone else who will drive the flow. For instance if we make the chat application event based then the flow of the program will go something as below:-
  1. End user sends chat message.
  2. User continues with his work ahead.
  3. Application listens to events. If a message arrives event is activated and message is received and displayed.



If you see the program flow it’s not sequential, its event based.  So now the control is inverted. So rather than the internal program controlling the flow, events drive the program flow. Event flow approach is more flexible as their no direct invocation which leads to more flexibility.

A word of caution here, do not conclude that IOC are implemented by only events.  You can delegate the control flow by callback delegates, observer pattern, events, DI (Dependency injection) and lot of other ways.

IOC (Inversion of control) is a general parent term while DI (Dependency injection) is a subset of IOC. IOC is a concept where the flow of application is inverted.   So for example rather than the caller calling the method.

SomeObject.Call();

Will get replaced with an event based approach as shown below.

SomeObject.WhenEvent += Call();

In the above code the caller is exposing an event and when that event occurs he is taking action.  It’s based on the Hollywood principle “Don’t call us we will call you”.  In Hollywood when artists used to give auditions the judges would say them “Don’t call us we will call you”.

The above approach makes code more flexible as the caller is not aware of the object methods and the object is not aware of caller program flow.





DI provides objects that an object needs.  So rather than the dependencies construct themselves they are injected by some external means.  For instance let’s say we have the following below class “Customer” who uses a “Logger” class to log errors. So rather than creating the “Logger” from within the class, you can inject the same via a constructor as shown in the below code snippet.



The biggest benefit achieved by the above approach is “Decoupling”. You can now invoke the customer object and pass any kind of “Logger” object as shown in the below code.

Customer obj = new Customer(new EmailLogger());
Customer obj1 = new Customer(new EventViewerLogger());