Compute value of string that has numbers seperated by arithmetic operators.

One of my friends recently went to an interview to a very well known startup company. It is supposed to hire only the very best technical people in the industry.  One of the problems that he was asked to write a unit test was,

Suppose a string has numbers separated by arithmetic operators, how do you compute the value of it?

BTW, I personally feel that you are not really testing the knowledge of a person by asking such questions and expecting them to solve it in 6 minutes.

Solution

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Data;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var operator1= new Operator();
            int result = operator1.Maths("2+3");
            Assert.AreEqual(result, 5);
        }

        [TestMethod]
        public void TestMethod2()
        {
            var operator1 = new Operator();
            int result = operator1.Maths("2+3*4");
            Assert.AreEqual(result, 14);
        }
        [TestMethod]
        public void TestMethod3()
        {
            var operator1 = new Operator();
            int result = operator1.Maths("2+3*10/5");
            Assert.AreEqual(result, 8);
        }
    }

    public class Operator
    {
        public int Maths(string operation)
        {
            object result=new DataTable().Compute(operation, null);
            return Int32.Parse(result.ToString());
        }
    }
}
Continue Reading

Adapter Pattern with a twist

One of my friends recently went to an interview to a very well known startup company. It is supposed to hire only the very best people in the industry.  One of the problem that he was asked to white board was:

You have a robot that can turn left and right. It can also move forward and backwards. You have a legacy robot that can only turn right and move forward. You want the legacy robot to turn left and to move backwards. Design a adapter class that would allow the legacy robot to turn right and to move backwards.

Solution

Adapter Design Pattern With A Twist

using System;
using System.Collections.Generic;
using System.Linq;
public interface IRobot
{
    void GoFront(int noOfSteps);
    void GoBack(int noOfSteps);
    void TurnRight(int degrees);
    void TurnLeft(int degrees);
}
public class LegacyRobot
{
    public void GoFront(int noOfSteps)
    {
    }
    public void TurnRight(int degrees)
    {
    }
}
public class Robot : IRobot
{
    public void GoFront(int noOfSteps)
    {
    }
    public void GoBack(int noOfSteps)
    {
    }
    public void TurnRight(int degrees)
    {
    }
    public void TurnLeft(int degrees)
    {
    }
}
public class LegacyRobotAdapter : IRobot
{
    LegacyRobot legacyRobot;
    public LegacyRobotAdapter(LegacyRobot legacyRobot)
    {
        this.legacyRobot = legacyRobot;
    }
    public void GoFront(int noOfSteps)
    {
        this.legacyRobot.GoFront(noOfSteps);
    }
    //The legacy robot can go back by turning right by 180 degrees
    //then going front by the number of steps requested by the client
    //then turning right by 180 degrees to be facing from where the robot started from. 
    public void GoBack(int noOfSteps)
    {
        this.legacyRobot.TurnRight(180);
        this.legacyRobot.GoFront(noOfSteps);
        this.legacyRobot.TurnRight(180);
    }
    public void TurnRight(int degrees)
    {
        this.legacyRobot.TurnRight(degrees);
    }
    //The legacy robot can turn left by turning right by 360 degrees minus the client requested degrees to turn
    public void TurnLeft(int degrees)
    {
        this.legacyRobot.TurnRight(360 - degrees);
    }
}
Continue Reading

Ensure a class has only one instance and provide a global point of access to it(Singleton Pattern)

Singleton Pattern:
Ensure a class has only one instance and provide a global point of access to it.

Solution:
The code below uses Double-checked locking. See here for an explanation of double checked locking.
Update(06/29/2016):
Jon Skeet’s article here, does not recommend implementing singleton pattern using Solution 1 below.
He instead recommend’s using .NET 4’s Lazy type, to implement a singleton pattern. The Lazy class internally uses double-checked locking by default to store either the exception that was thrown during construction, or the result of the function that was passed to Lazy.
I have implemented the same in Solution 2 below.

Solution 1(Not recommended):

Singleton Design Pattern

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
public class UnitTest1
{
        [TestMethod]
        public void SingletonTest()
        {
            var s1 = Singleton.Instance();
            var s2 = Singleton.Instance();

            if (s1 == s2)
            {
                Assert.IsTrue(true);
            }
            else
            {
                Assert.Fail();
            }
        }
}
public class Singleton
{
    private static Singleton singleton;
    private static object tempObjectForLocking = new object();
    private Singleton()
    {
    }
     public static Singleton Instance()
     {
            if (singleton != null)//First check
            {
                return singleton;
            }
            lock (tempObjectForLocking)
            {
                //Multiple processes could access the code below at the same time, 
                //therefore a "null" check has been added so only one process 
                //can create a singleton instance. 
                if (singleton == null)//Second(double) check
                {
                    singleton = new Singleton();
                }
            }
            return singleton;
     }
}

Solution 2(recommended):

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
public class UnitTest1
{
        [TestMethod]
        public void SingletonTest()
        {
            var s1 = Singleton.Instance();
            var s2 = Singleton.Instance();
            if (s1 == s2)
            {
                Assert.IsTrue(true);
            }
            else
            {
                Assert.Fail();
            }
        }
}
public sealed class Singleton
{
    //Using the .NET 4's Lazy<T>; type, to implement a singleton pattern. 
    //The Lazy<T>; class internally uses double-checked locking by default to 
    //store either the exception that was thrown during construction, 
    //or the result of the function that was passed to Lazy<T>.

    private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>
    (
      () => new Singleton()
    );    
    public static Singleton Instance 
    { 
      get 
      { 
        return lazy.Value; 
      } 
    }
    private Singleton()
    {
    }
}
Continue Reading

Avoid accidentally throwing a NullReferenceException and null object checking code(Null Object Pattern)

Null Object Pattern:
Avoid accidentally throwing a NullReferenceException and null object checking code by using the Null Object design pattern.

using System;
using System.Linq;
    public static class StringExtensions 
    { 
        public static int GetSafeLength(this string valueOrNull) 
        { 
            return (valueOrNull ?? string.Empty).Length; 
        }
    }
    public static class Program 
    {
        static readonly string[] strings = new [] { "ajit", "goel", null, "kumar" };
        public static void Main(string[] args) 
        {
            //no need to do any checks here
            var query = from text in strings select text.GetSafeLength(); 
            Console.WriteLine(query.Sum());
        }
    }
Continue Reading

SOLID Principles in Brief

SOLID is a term describing a collection of design principles for good code. It was invented by Robert C. Martin(Uncle Bob).

SOLID means:
a. Single Responsibility Principle
b. Open/Closed Principle
c. Liskov Substitution Principle
d. Interface Segregation Principle
e. Dependency Inversion Principle

a. Single Responsibility Principle
Single Responsibility Principle states that every class should have a single responsibility. There should never be more than one reason for a class to change.

//This class violates Single Responsibility Principle since this class is doing two
//things. It is dealing with both opening \ closing connections and with 
//data communication.
public interface IDatabase
{
    void Connect(string connectionString);
    void Close();
    object GetData();
    void SendData(object data);
}

Refactored code to follow Single Responsibility Principle and Open\closed principle:

//IDatabase class has now been refactored into two classes. The IDataManager 
//class deals with data communication.The IConnectionManager 
//class deals with opening \ closing connections. These classes now follow the 
//Single Responsibility Principle.
public interface IDataManager
{
    object GetData(IConnectionManager connManager);
    void SendData(IConnectionManager connManager, object data);
}
public interface IConnectionManager
{
    void Connect(string connectionString);
    void Close();
}

b. Open/Closed Principle
Open/Closed Principle states that software entities should be open for extension, but closed for modification.

In the example above, refactoring IDatabase into IConnectionManager, IDataManager classes allows the client application to either
a. if the client application likes to change the way it opens or closes connection, it can implement its own IConnectionManager and pass it to the IDataManager class i.e Without touching the original code, it is able to extend the functionality of the classes without actually breaking the already existing class.
b. if the client application likes to change the way its getting or sending data it can implement its own IDataManager and use it with the already existing implementation of IConnectionManager.

c. Liskov Substitution Principle
Liskov Substitution Principle states that code should not know it is using base class or its subtypes.

public class DatabaseRepository
{
    //This method violates Liskov Substitution Principle since it consumes an object 
    //of a base type but internally uses the base type's subclass. According to 
    //Liskov Substitution Principle, it should not know it is using base class 
    //or its subtypes. 
    public bool TestConnection(IConnectionManager connMngr)
    {
        if (connMngr is SqlServerConnectionManager)
        {
            // Do something...
        }
        else if (connMngr is OracleConnectionManager)
        {
            // Do something else...
        }
        else
        {
            // ...
        }
    }
}
public interface IConnectionManager
{
    void Connect(string connectionString);
    void Close();
}
public class SqlServerConnectionManager: IConnectionManager
{
    public void Connect(string connectionString)
    {
    }
    public void Close()
    {
    }
}
public class OracleConnectionManager : IConnectionManager
{
    public void Connect(string connectionString)
    {
    }
    public void Close()
    {
    }
}

d. Interface Segregation Principle
The Interface Segregation Principle states that clients should not be forced to implement interfaces they don’t use.

Existing Design
Let’s assume we have to implement a new Robot class in this design. Robots will need to implement the IWorker interface because robots works. On the other side, they don’t have to implement it because they don’t eat. If we keep the present design, the new Robot class is forced to implement the “eat” method.

public interface IWorker 
{
	public void Work();
	public void Eat();
}
public class Worker : IWorker
{
	public void Work() 
        {
	}
	public void Eat() 
        {
	}
}
public class Manager 
{
	IWorker worker;
	public void SetWorker(IWorker w) 
        {
		worker=w;
	}
	public void Manage() 
        {
		worker.Work();
	}
}

Interface Segregation Principle implemented in current design

//Following code supports the Interface Segregation Principle. By splitting the 
//IWorker interface in IFeedable, IWorkable interfaces the new Robot class is 
//no longer forced to implement the "eat" method.
public interface IWorker : IFeedable, IWorkable 
{
}
public interface IWorkable 
{
	public void Work();
}
public interface IFeedable
{
	public void Eat();
}
public class Worker : IWorkable, IFeedable
{
	public void Work() 
        {
	}
	public void Eat() 
        {
	}
}
public class Robot : IWorkable
{
	public void Work() 
        {
	}
}
public class Manager 
{
	IWorkable worker;
	public void SetWorker(IWorkable w) 
	{
		worker=w;
	}
	public void Manage() 
	{
		worker.Work();
	}
}

e. Dependency Inversion Principle
Dependency Inversion Principle states that
1. High-level modules(Manager class) should not depend on low-level modules(Worker, SuperWorker classes). Both(Manager, Worker, SuperWorker classes) should depend on abstractions(IWorker).
2. Abstractions should not depend on details. Details should depend on abstractions.

Existing Design
Let’s assume we have to implement a new SuperWorker class in this design. If we do that then we will have to change the Manager.Manage() method also which introduces risk.

public class Worker 
{
	public void Work() 
	{
	}
}
public class SuperWorker: Worker 
{
	public void Work() 
	{
	}
}
public class Manager 
{
	Worker worker;
	public void SetWorker(Worker w) 
	{
		worker = w;
	}
	public void Manage() 
	{
		worker.Work();
	}
}

Dependency Inversion Principle implemented in current design

//Following code supports the Dependency Inversion Principle. In this new design 
//a new IWorker Interface has been added. Now the Manager class doesn't require 
//changes when SuperWorkers are added since the work has been delegated to the 
//SuperWorker class.It also reduces risk since no other parts of the system need 
//to be tested.
public interface IWorker 
{
	public void Work();
}
public class Worker : IWorker
{
	public void Work() 
	{
	}
}
public class SuperWorker : IWorker
{
	public void Work() 
	{
	}
}
public class Manager 
{
	IWorker worker;
	public void SetWorker(IWorker w) 
	{
		worker = w;
	}
	public void Manage() 
	{
		worker.Work();
	}
}

Dependency Injection is about how one object acquires a dependency.
Inversion of Control (IoC) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source (for example, an xml configuration file).
Dependency Injection (DI) means that this is done without the object intervention, usually by a framework component that passes constructor parameters and set properties.

Dependency Injection Container is a way to auto-wire classes

Continue Reading

Database performance tuning concepts in brief

Predicates are used to used to specify a subset of rows to be returned. They are specified in the WHERE clause of a SQL statement.
In the example below “Id = 1” is a predicate:

SELECT * FROM Employee WHERE Id = 1;

Estimated Execution Plan defines how a query should actually execute
Actual Execution Plan tells what happened while a query was executed.
Table Scan/Index Scan looks at each and every row available in the table/index
Index Seek has address of each row based on the key field value. So seek directly goes to that data page and fetches the row if your predicate matches with the key field.
Key Lookup, In case of Key lookup, SQL server storage engine has to go from non-clustered index to clustered index, in order to fetch the value of non-key field of non-clustered index. This round-trip always consumes time and decreases performance.

Continue Reading

Tips to increase database performance

Here are some of the points that you should consider when you write queries:

  • Limit number of rows and columns
  • Use “Search argument able” conditions in “where” clause. They help query optimizers to use the index defined on column(s) effectively and have a higher chance of meeting index seek than index or table scan.
    “Search argument able” operators are :
    =, >, >=,
  • Do not use arithmetic operators directly on the “column name” in the “where” clause. Instead use logical workarounds to get performance benefits. eg:
    instead of
    WHERE HourlyRate * 8 <= 100

    use

    WHERE HourlyRate <= 100/8
  • Do not use functions on columns in the “where” clause. eg:
    a. Instead of
    WHERE DATEPART(YYYY,CreateDate)='2016'

    use

    WHERE CreateDate >= '01/01/2016' AND CreateDate <= '12/31/2016'
  • b. Instead of

    WHERE Left(LastName,1)='A'

    use

    WHERE LastName LIKE 'A%'
  • Use proper primary and Foreign Key constraints. They help the query optimizer select the best-suited execution plan for the query.
  • Here are some of the points that you should consider when designing indexes.

  • Try to use maximum 4-5 indexes on one table, not more. If you have read-only table, then the number of indexes may be increased.
  • Keep your indexes as narrow as possible. This reduces the size of the index and reduces the number of reads required to read the index.
  • Try to create indexes on columns that have integer values rather than character values.
  • If you create a composite (multi-column) index, the order of the columns in the key are very important. Try to order the columns in the key as to enhance selectivity, with the most selective columns to the leftmost of the key.
  • Continue Reading

    Distinct on multiple properties in a collection

    Problem:
    How do I get distinct members of a collection, based on multiple properties?

    Solution:
    Use MoreLinq to get distinct members of a collection, based on multiple properties.
    eg: For our application, each member in the household was supposed to have a unique combination of driver’s licence number and driver’s state.

     
    var query = household.DistinctBy(
                counter => new { counter.DriverLicenceNumber, counter.DriverLicenceState });
    
    Continue Reading

    Configure StructureMap for Asp.Net MVC

    Problem:
    How do I configure StructureMap for Asp.Net MVC?

    Solution:
    a. Install StructureMap using NuGet and the following command.

    install-package StructureMap.MVC5 
    

    Once StructureMap is installed, you’ll notice several additions to your web project including a new “DependencyResolution” folder.

    Dependency Injection

    b. Create a new interface. Implement this interface with a new class.

     public interface IDependency
        {
            string SayHelloWorld();
        }
        public class Dependency : IDependency
        {
            public string SayHelloWorld()
            {
                return "Hello World";
            }
        }
    

    c. Have the Controller work with this interface:

    public class HomeController : Controller
    {
        private readonly IDependency dependency;
        public HomeController(IDependency dependency)
        {
            this.dependency = dependency;
        }
        public ActionResult Index()
        {
            return Content(this.dependency.SayHelloWorld());
        }
    }
    

    d. Run your application.The “Concrete Dependency” is successfully injected in HomeController.
    Dependency Injection-Results

    We didn’t tell StructureMap how to resolve the “IDependency” interface, or let it know anything about the “Dependency” implementation. How did it figure this out?

    In the DefaultRegistry.cs file, there is a line of code that reads

    scan.WithDefaultConventions();
    

    This code will automatically attempt to resolve any interface named “IDependency” with an instance type named “Dependency”. That is, the same name, but without the “I” prefix. If instead the name of the class was “ConcreteDependency” then the code below will not work. in this case, you will have to specify the types explicitly.You would do that by adding.

    For<IDependency>().Use<ConcreteDependency>();
    

    It is commented out in the DefaultRegistry.cs code

    public class DefaultRegistry : Registry 
    {
            public DefaultRegistry() 
            {
                Scan(
                    scan => 
                    {
                        scan.TheCallingAssembly();
                        scan.WithDefaultConventions();
                        scan.With(new ControllerConvention());
                    });
                    //For<IDependency>().Use<ConcreteDependency>();
            }
    }
    
    public static class IoC
        {
            public static IContainer Initialize()
            {   
                return new Container(c => c.AddRegistry<DefaultRegistry>());
            }
        }
    
    Continue Reading

    Show traffic from only certain hosts in Fiddler

    A lot of times when we “show traffic” in Fiddler, way too much traffic gets logged. To cut the “noise” out, we want to show traffic from only certain hosts. To do this:

    • Check the “use filters” checkbox.
    • In the “Show only the following hosts” textbox, type the names of the hosts separated by colon.
    • If you have several similar hosts then you can use wildcards also.
      Example: If you want to log the requests for drive.realpage.com, photos.realpage.com then instead of listing each one of them, you can use *.realpage.com. See below for an example

    FiddlerFiltersTab

    Continue Reading