Wednesday, September 11, 2013

C# Lazy loading interview questions with answers




What is Lazy loading ?

Lazy loading is a concept where we delay the loading of the object unit the point where we need it. Putting in simple words on demand object loading rather than loading the objects unnecessarily.

For example consider the below example where we have a simple “Customer” class and this “Customer” class has many “Order” objects inside it. Have a close look at the constructor of the “Customer” class. When the “Customer” object is created it also loads the “Order” object at that moment. So even if we need or do not need the address object, it’s still loaded.

But how about just loading the “Customer” object initially and then on demand basis load the “Order” object.

public class Customer
{
private List _Orders= null;
public Customer()
{
            _CustomerName = "Shiv";
            _Orders = LoadOrders(); // Loads the address object even though //not needed
          
}
    
private List LoadOrders()
{
            List temp = new List();
            Order o = new Order();
            o.OrderNumber = "ord1001";
            temp.Add(o);
            o = new Order();
            o.OrderNumber = "ord1002";
            temp.Add(o);
            return temp;
}

}

So let’s consider you have client code which consumes the “Customer” class as shown below. So when the “Customer” object is created no “Order” objects should  be loaded at that moment. But as soon as the “foreach” loop runs you would like to load the “Order” object at that point ( on demand object loading).

Customer o = new Customer(); // Address object not loaded
Console.WriteLine(o.CustomerName);
foreach (Order o1 in o.Orders) // Load address object only at this moment
{
Console.WriteLine(o1.OrderNumber);
}

So how do we implement “LazyLoading” ?

So for the above example if we want to implement Lazy loading we will need to make the following changes:-
  • Remove the “Order” object loading from the constructor.
  • In the “Order” get property, load the “Order” object only if it’s not loaded.
public class Customer
{
private List _Orders= null;

public Customer()
{
            _CustomerName = "Shiv";          
}

public List Orders
{
      get
        {
                if (_Orders == null)
                {
                    _Orders = LoadOrders();
                }
                return _Orders;
        }
          
}

Now if you run the client code and halt your debugger just before the “ForEach” loop runs over the “Orders” object, you can see the “Orders” object is null ( i.e. not loaded). But as soon as the “ForEach” loop runs over the “Order” object it creates the “Order” object collection.


Are there any readymade objects in .NET by which we can implement Lazy loading?

In .NET we have “Lazy” class which provides automatic support for lazy loading. So let’s say if you want to implement “Lazy<>” in the above code we need to implement two steps for the same:-

Create the object of orders using the “Lazy” generic class.

private Lazy> _Orders= null;

Attach this Lazy<> object with the method which will help us load the order’s data.

_Orders = new Lazy>(() => LoadOrders());

Now as soon as any client makes a call to the “_Orders” object ,it will call the “LoadOrders” function to load the data.

You will get the “List” data in the “Value” property.

        public List Orders
        {
            get
            {
                return _Orders.Value;
            }
          
        }

Below goes the full code for the same.

public class Customer
{
private Lazy> _Orders= null;

        public List Orders
        {
            get
            {
                return _Orders.Value;
            }
          
        }
 public Customer()
        {
            // Makes a database trip
            _CustomerName = "Shiv";
            _Orders = new Lazy>(() => LoadOrders());
          
        }
}

What are the advantages and disadvantages of lazy loading?

Below are the advantages of lazy loading:-
  • Minimizes start up time of the application.
  • Application consumes less memory because of on-demand loading.
  • Unnecessary database SQL execution is avoided.

The only one disadvantage is that the code becomes complicated. As we need to do checks if the loading is needed or not. So must be there is a slight decrease in performance.

But the advantages of are far more than the disadvantages.

FYI :- The opposite of Lazy loading is Eager loading. So in eager loading we load the all the objects in memory as soon as the object is created.



Friday, September 6, 2013

What is cyclomatic complexity (C# testing interview questions with answers)?

Cyclomatic complexity helps you measure code complexity.  Higher the code complexity, more it is prone to errors and more important it becomes to unit test that specific code.

Cyclomatic complexity number depends on how many different execution paths your code can execute depending on varying inputs. More the code paths, more the complexity.

For example take the below code. There is nothing complex in the below code, we do not have many execution paths. We just have lots of code lines which does variable initialization.  So the cyclomatic complexity of the below code is “1”.

public void Cancel()
{
            Num1 = 0;
            Num2 = 0;
            Operation = "";
            Pie = 3.14;
            Num5 = 0;
            Operation1 = "";
            Num20 = 0;
            Numx = 0;
            OperationStart = "";
            PieMore = 3.145;
            Num6 = 0;
            Operationnew = "";
}

But now take the example of below code. There are 4 branch conditions in the below code as shown in the below table. So the cyclomatic complexity is “4”.


Input
Output
Path 1
Operation.Length ==0
Exception thrown
Path 2
Operation == “+”
Num1 + Num2
Path 3
Operation == “-“
Num1 – Num2
Path 4
Any other inputs
Num1 * Num2


public int Calculate()
        {
            if (Operation.Length == 0)
            {
                throw new Exception(" Operation not sepecified");
            }
                if (Operation == "+")
                {
                    return Num1 + Num2;
                }
                else if (Operation == "-")
                {
                    return Num1 - Num2;
                }
                else
                {
                    return Num2 * Num1;
                }
                return 0;

        }

To measure code complexity using visual studio , click on Analyze à Calculate code metric for the solution. This feature is available only for VS ultimate editions. Once done you should get the cyclomatic complexity as shown in the below figure. 




Sunday, September 1, 2013

What are portable class libraries? ( .NET interview questions with answers)

This interview question is taken from the famous .NET interview question with answer book published by Bpb publications.

The whole point of creating a class library project is reusability. Now we want this reusability not only within a .NET application, not across .NET applications but across different types of .NET applications. Now different types of .NET application means WPF, Windows, Silver light, Windows phone etc.


Now each one of these applications run on different platforms and have different flavors of .NET frameworks. For example silver light application runs inside a browser and has a down sized version of .NET.

So in a silver light application if you try to reference a simple “Class project” you would end with a below error. That’s where portable class libraries are useful. By creating a portable class we can reference it in any kind of .NET project types.


To create a portable class we need to use the portable class template which is available in visual studio as shown in the below figure.



We are thankful to questpond.com to provide financial support for this site. Questpond.com has interview question videos on C# , .NET, MVC, ASP.NET , SQL Server and design patterns.

Below is a simple youtube video which demonstrates What are Portable Class library in c#.