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#.

Wednesday, August 21, 2013

Fluent interfaces and Method Chaining in C#



Humans are lazy and programmers are humans J . We like things which are simplified and clean. So if you see the evolution of programming, we initially started with functional programming, and evolved towards object oriented programming.

So as functional programmers where we used to remember methods and function names like “Add”, “Subtract”, “Multiply” and “Divide”, in OOP we just need to remember class “Maths” and all functions just pop out when we create the object of the class.

But as object oriented programmers we need to remember there are two worlds in OOP, one who creates the class and second who consumes it by creating the object.

So by following good OOP principles like abstraction, encapsulation etc developer writes the below “Customer” class so that other developers who consume this class should not feel it complicated.

public class Customer
    {
        private string _FullName;

        public string FullName
        {
            get { return _FullName; }
            set { _FullName = value; }
        }

        private DateTime _Dob;

        public DateTime Dob
        {
            get { return _Dob; }
            set { _Dob = value; }
        }

        private string _Address;

        public string Address
        {
            get { return _Address; }
            set { _Address = value; }
        }
  
    }

Now the consumer who want to consume our “Customer” class will create the customer object , set properties and invoke methods.  Below is the sample code for the same.


Customer customer = new Customer();
customer.FullName = "Shiv";
customer.Dob = Convert.ToDateTime("1/1/2008");
customer.Address = "Mumbai";

Now let’s zoom on the above consumer code. Is it complicated?, probably not if you are C# developer or a object oriented programmer.

But what if your consumer is a tester who really does understand c# and would like to have more simplified interfaces to invoke your customer class for UNIT testing purpose.

What if you are component seller and you would like to surprise your component consumers with simplified interfaces. You would like to stand different from your competitors.

Welcome to the concept of “Fluent interfaces”.

“Fluent interfaces simplify your object consumption  code by making your code more simple, readable and discoverable.”

So if our component consumers can write object invocation code in simple English sentence like below , that would “ROCK” right.


customer.NameOfCustomer("Shiv")
                .Bornon("12/3/1075")
                .StaysAt("Mumbai");

So now the next thing how to we implement “Fluent” interfaces. That’s done by using “Method chaining”.

“Method chaining” is a common technique where each method returns an object and all these methods can be chained together to form a single statement.

So the above customer class we can wrap in another class (“CustomerFluent”) which will implement method chaining and expose chained methods in a simplified format.

So you can see in the below code methods “NameofCustomer” , “BornOn” accept input s and return backs “CustomerFluent” class.

public  class CustomerFluent
    {
        private Customer obj = new Customer();
        public CustomerFluent NameOfCustomer(string Name)
        {
            obj.FullName = Name;
            return this;
        }
        public CustomerFluent Bornon(string Dob)
        {

            obj.Dob = Convert.ToDateTime(Dob);
            return this;
        }

        public void StaysAt(string Address)
        {
            obj.Address = Address;
           
        }
    }

Now your client code is simple, nice and FLUENT as in the below code.

customer.NameOfCustomer("Shiv")
                .Bornon("12/3/1075")
                .StaysAt("Mumbai");

I have seen four visible uses of fluent interfaces:-

LINQ Queries

var x = context.Users.Select(u => new { u.Id, u.Name });

Unit testing

Assert.AreEqual(obj.Expected,obj1.Actual);

Mock testing

Container.GetMock()
                  .Setup(s => s.Save(new Person()))
                  .Returns(true)
                  .Verifiable();

DSL (Domain specific language)

DSL is a language for simple users who do not understand programming. So they can type something in simple English as shown below. This will be parsed and checked for syntaxes. Later this sentence can be mapped to a internal fluent interface statement.

task "warn if website is not alive":
      every 1.Hour
      starting now
      when WebSite("http://www.questpond.com ").IsAlive is false
      then:notify "admin@example.org", "site down!"

Below is the code of the Fluent interface statement to which the above DSL can map.

new FluentTask("alert if site is down")
      .Every( TimeSpan.FromMinutes(3) )
      .StartingFrom( DateTime.Now )
      .When(delegate
      {
            return WebSite("http://www.questpond.com").IsAlive == false;
      })
      .Execute(delegate
      {
            Notify(“admin@example.org”, “site down!”);
      });

Are Fluent interfaces always good?

If you are creating fluent interfaces for developers then probably you are wasting time. Developers are consistent with creating objects with the new keyword and setting properties.  Even if you create something simple for them they are consistent with certain consuming methodology and you will find you are adding more complexity than simplifying it. 

Second thing we need to understand that we need to write more amount of code to create fluent interfaces. As you saw in the previous code I created a separate class for making interfaces simplified.

There are very few instances when you need fluent interfaces, below are few of them:-
  • During UNIT testing when the developers are not full fledged programmers.
  • You want your code to be readable by non-programmers so that they can understand if the code is satisfies their domain logic.
  • You are component seller and you want to stand out in the market as compared to the others by making your interfaces simpler.
  • You are creating a DSL language and this language is mapped with fluent interface statements.







    

Sunday, August 18, 2013

C# Design pattern interview questions: - What are fluent interfaces and method chaining?

Fluent interfaces simplify your object consumption code by making your code more simple, readable and discoverable.

So for instance let’s say you have a customer class with properties like “FullName” , “Dob”, and “Address”. If you want to consume the class you would write something as shown below.

Customer customer = new Customer();
customer.FullName = "Shiv";
customer.Dob = Convert.ToDateTime("1/1/2008");
customer.Address = "Mumbai";

But if you use fluent interfaces your client consumption code can be simplified as shown below.

customer.NameOfCustomer("Shiv")
                .Bornon("12/3/1075")
                .StaysAt("Mumbai");


So how to implement Fluent interfaces?

One of the most common way of implementing fluent interface is by using “Method Chaining”. For example below is a simple “Customer” class and let’s say we want to implement fluent interface on the top of it.

public class Customer
    {
        private string _FullName;

        public string FullName
        {
            get { return _FullName; }
            set { _FullName = value; }
        }

        private DateTime _Dob;

        public DateTime Dob
        {
            get { return _Dob; }
            set { _Dob = value; }
        }

        private string _Address;

        public string Address
        {
            get { return _Address; }
            set { _Address = value; }
        }
  
    }

So we can use method chaining. 

“Method chaining” is a common technique where each method returns an object and all these methods can be chained together to form a single statement.

So the above customer class we can wrap in another class (“CustomerFluent”) which will implement method chaining and expose chained methods in a simplified format.

So you can see in the below code methods “NameofCustomer” , “BornOn” accept input s and return backs “CustomerFluent” class.

public  class CustomerFluent
    {
        private Customer obj = new Customer();
        public CustomerFluent NameOfCustomer(string Name)
        {
            obj.FullName = Name;
            return this;
        }
        public CustomerFluent Bornon(string Dob)
        {

            obj.Dob = Convert.ToDateTime(Dob);
            return this;
        }

        public void StaysAt(string Address)
        {
            obj.Address = Address;
           
        }
    }

So now your client code becomes something like below.

customer.NameOfCustomer("Shiv")
                .Bornon("12/3/1075")
                .StaysAt("Mumbai");

You can watch our design pattern interview question videos from questpond.com

  

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.