Tuesday, December 31, 2013

What is IOC and Dependency injection and how do they differ from each other?(Design pattern interview questions with answers)

When we talk about software programs they have LOGIC’s and LOGIC’s have FLOW. Take the below simple code. We have a “Customer” class which is instantiated from a console application.

class Customer
    {
        private SQLServer Dal = new SQLServer();
        public bool validate()
        {
            return true;
        }
        public void Add()
        {
            if (validate())
            {
                Dal.Add();
            }
        }
    }
    class SQLServer
    {
        public void Add()
        {
        }
    }

Customer obj = new Customer();
obj.Add();

If you watch the program flow of the customer object it is as follows:-
  • Client creates object of the customer class.
  • Customer class creates the object of SQL Server data access layer.
  • Customer object then invokes “Validate” method.
  • Once the “Validate” method is successful then it invokes the “Add” method.


In other words the “Customer” class is in control of his FLOW. Now let us complicate the situation.  Let’s say we have different flavors of data access layer.  So let’s say we have “SqlServer” and “Oracle” as shown below.

So the best way to implement the same is my creating a generic interface “Dal” and pointing that generic interface to “SQLServer” or “Oracle” object depending on situations. So if you see the flow now:-
  • Client creates object of the customer class.
  • Customer class depending on configuration decided to create SQL Server object or Oracle object.
  • Customer object then invokes “Validate” method.
  • Once the “Validate” method is successful then it invokes the “Add” method.


A good code is that code which takes care of his own logic rather than overloading with logic which he is not concerned with. For instance in this case the customer class is now taking care of logics like deciding which data access layer objects to be created.

class Customer
    {
        private Dal dal;
        public Customer(int DalType)
        {
            if (DalType == 1)
            {
                dal = new SQLServer();
            }
            else
            {
                dal = new Oracle();
            }
        }
        public bool validate()
        {
            return true;
        }
        public void Add()
        {
            if (validate())
            {
                dal.Add();
            }
        }
    }

interface Dal
    {
        void Add();
    }
    class SQLServer : Dal
    {
        public void Add()
        {
        }
    }
    class Oracle : Dal
    {
        public void Add()
        {
            throw new NotImplementedException();
        }
    }

This makes the customer class tightly coupled to the data access layer changes and second in long run this code becomes difficult to maintain. So the solution here  is customer class should perform his own concerned logic like validating customer class , calling add method of data access layer. But deciding which data access layer to create is not his part.

So if this logic or this control is given to some other entity or can be INVERTED to some one else then the code would look much better.


So if we change the code to something as shown below. Where the customer class say’s hey  look I am not concerned its Oracle or SQL Server. Pass me the generic interface object from the constructor and relieve me from the decision making logic of Data access layer.

class Customer
 {
        private Dal dal;
        public Customer(Dal obj)
        {
            dal = obj;
        }
      …
      …
}

So now it’s the work of client or the invoker to decide which data access layer object has to be passed.

If you visualize this scenario the flow of “Customer” class now takes care of his logic and the unconcerned logic is now passed to an external entity. This is termed as “Inversion of control”. The control or logic which is not part of that entity is taken care by someone else.

Also if you put in other terms the flow of “Customer” class is now affected by external entities depending on whether they inject “SqlServer” object or “Oracle” object.

A word of caution here, do not conclude that IOC can  only be implemented by exposing abstraction via constructor.  You can delegate the control flow by callback delegates, observer pattern, events, and lot of other ways.


The above way of sending abstraction from constructor is termed as “dependency” injection.IOC (Inversion of control) is a general parent term while DI (Dependency injection) is a subset of IOC.

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());

Inversion of control
Dependency injection
It’s a generic term and implemented in several ways (events, delegates etc).
DI is a subtype of IOC and is implemented by constructor injection, setter injection or method injection.













































































Sunday, October 6, 2013

So you want to be IT corporate trainer?

First let me admit that I am NOT A number one or an ace IT trainer , there are lot of trainers more experienced and better than me. But I do want to share some experiences which I feel can be useful for developers who want to jump in to IT corporate training. Its possible some of the experiences below are important for me and for other trainers they are just pint size.

Do not jump just for money
If you are motivated to jump in this field because some trainer said he earns 80 thousand per day, its better to stay away from this field.Training is a humble profession and you should have that attitude of sharingknowledge, delivering quality training and believe me rest, so called money will follow.

As a trainer the most satisfying thing is to see those satisfied eyes of participants saying “Yes, we benefitted”.


Jack of ALL master of none


For some people this point would look odd and weird. We need to understand we are in to training and not development. In development I do understand we want specialized skills. For example if you are doing web programming you would like developers who know ASP.NET and MVC in depth.

But in training if you just stick to one topic, I doubt you will be billable for a full month. I know one design pattern trainer, who just does design pattern. But how much DP courses are available across India and how much comes in his kitty is doubtful.

So you need to have an overall diversified portfolio spread across atleast 5 known and demanded technologies in corporate world.

A good timely paying vendor / marketing person is the KEY

This is the most difficult part, creating chemistry with a vendor / marketing person. Do not even think about going directly to companies at the first stage, it’s a long process. A good vendor pitches you , talks about you , markets you for months , so that you get the stage.

So be reasonable, let your vendor earn some money and you keep getting business.

Things slip between trainer and the vendor on the below two occasions:-

  • When the vendor does not pay on time. This is the case most of the time. I had my bitter experiences with vendors on the same issue. I have never looked back at those vendors again. Even if I am not getting work, its fine. I find it’s unethical to not pay trainers when you have already got money from the company.
  • When trainers does not perform. This is again one more place where things are wrong. If you think the training has crashed do not charge the vendor, say sorry, take the learning’s and improve in your next training. Believe me how good you are , you would have a day slip someday.

One more golden rule to remember with vendors, if a vendor delays more than 2 months, just stop training with him, I bet he will ever pay you. Just start hunting  new vendor, there are plenty of good ones.


Discuss, Discuss and Discuss


Once a vendor pitches you and the customer approves your profile. Take a call with the customer, discuss the complete agenda, understand what the customer wants. Ask him every detail right from software installation, type of participants, which topic to emphasize on etc.

Do not take the training just looking at the agenda its very much possible ground situations can be very different and challenging.

Before training


  • Mute your mobiles. Some participants consider phone ringing as a casual attitude of the trainer.
  • On the first day be present 1 hour before. Helps out to understand if images or installation have any issues. You are in charge, if any issues of installation happenit’s at the end of the day trainer’sproblem; believe me no one comes to rescue. Doing escalation just escalates the problem more.
  • Interact with the attendees and see how much in depth they know about the topic. If you have good experienced people that means your training bar has to rise higher. If you have lot of freshers , you can go with step by step approach.
  • Just revise what topics you will start with, what you will say and what you will demo. I do this in my mind when I travel to the training location.
  • If you are travelling outside ensure you have internet dongle (like tata docomo). Indian hotels do not have great internet connections. You will need it if someone asks weird doubts in between of the sessions.
  • Ensure you have access to Chalks, duster, projector blah blah. Especially ensure the chalks are not mild  in color and you have atleast two different colors so that you can make an effective presentation.
  • Some company stresses on attendance ensure those are at place. If not SMS the training co-coordinator.

During training


  • Ensure that at least90% people are present before you start the training or else you need to repeat topics for every person who comes later.
  • Start with a small introduction of what you do, do not over glorify yourself it just raises the training expectation higher. Let your training quality speak what you are.
  • Any topic you take from the agenda start with a bit of theory and then demos.Have three proper breaks in the whole day. People get fed up with 3 hours of movie, 8 hours of training is not entertaining.
  • While doing demos identify your weak participants focus more on them and ensure the good ones sail themself smoothly.
  • During lunch breaks and tea breaks ensure you sit with the team, get mixed with them , talk topics which are off technical and take mild feedbacks on how the training is proceeding.
  • There will be over demanding participants and some of the questions you would not be able to answer at that moment , note it ensure that you have the answer next day of the training. If it’s the last day ensure that you email him some pointers at least.

End of training


  • After all the hardwork you have done during the day ,  good rating is your expectation. Make a mild ( extremely mild ) request to participants that if they want you to see you back and if they feel you have done worth job , let it reflect in the feedback. Always remember in many organizations a good feedback means you get paid.
  • Flash your contact details, facebook , email id , twitter etc. Be in touch with the participant, who knows you come back to the same premise, knowing someone can just help you later.

Look after your health and Family first

  • Most of the time as trainer your half-life goes in hotels. Ensure when you reach hotel, do a bit of warm up , yoga or something. Eat light food, avoid drinks and sleep well.FYI I have myself not been able to control drinks and its horrible next day . 
  • Call you family before and after the training , they are the people who miss you most.
  • Take gaps between training , do not over book your schedule.

From trainer to a vendor
  • After working for some time many trainers get this feeling to start on their own. It’s not that you should not start on your own but ensure that you have good marketing partner with you who takes care of all the other things. Ensure you have a trainer pool which means you need to feed them with salaries every month.
  • Have good contacts of freelancer trainers who are professional and committed. Most important pay them on time, remember at one point you were also trainer.










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.