Saturday, March 22, 2014

Temp variablesVS Temp tables(SQL Server interview questions)



Temp tables
Temp variables
Big difference
Temp tables are real temporary SQL Server tables , you can create indexes , they can participate in transactions , it will use SQL Server optimization techniques etc.
So if you are operating on large number of records use Temp tables.
As the name says these are variables. So they do not participate in transactions, you can not create indexes directly, they do not use SQL server optimization techniques etc.


Good for small number of records.
Should be used when?
Large number of records.
Less than 100 records.
Scope
Outside procedure
Only Inside the procedure.
Transaction
Yes
No
Indexes
Yes
No (Note: - Indexes get indirectly created if you great a unique primary key.)
Truncate
Yes
No
Alter Table
Yes
No it’s just variable.
Affected by SQL Server optimization
Yes
No
Parallelism
Yes
No.
 
Recently one of our friends was asked this tricky SQL Server interview question: - Can SQL Server views be updated ?. Below is a great video by www.questpond.com which discusses this question in detail.

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.