Thursday, September 24, 2015

Module Pattern in Javascript

In today's post, I will be discussing the basic Module pattern in JavaScript. It is a well known coding pattern in JavaScript and if you have written some front-end code, you might already be familiar with this.

Module Pattern

As we know we do not have access modifiers (e.g. private, public) in JavaScript. In other languages, we can have our private and public variables to control the visibility and hide the implementation details. In JavaScript, we can use the module pattern to emulate the concept of classes. By using this, we can return the specific parts which we want to expose and hide the particular parts from global scope. Let's move along with an example to understand the Module pattern:

Suppose, we have an object literal like this:

var dom = {

    _counter : 0,

    generateId: function(){

        return 'custom' + this._counter++;

    },

    create: function(tagName){

        var el = document.createElement(tagName); 

        el.Id = this.generateId();

        return el;

    }

}


As you can see we have two methods exposed: create() and generateId(). The expected usage of this is to create new objects using create() method. Inside the create method, we create a new element,  assign an id to the element and return it.

So we simply create two buttons like this:

var el1 = dom.create('button');

var el2 = dom.create('button');

document.writeln(el1.Id);

document.writeln(el2.Id);


And if we look at the outputs, we will see custom0 and custom1. So that's good for our purpose and should suffice.

However, as you can see, we have exposed the counter and generateId methods as well which were not needed to be exposed. This can be bad. For example, setting the counter variable to some bad value might interfere with the normal execution of the program.

For example, if we set

dom._counter = 'abcd'

var el1 = dom.create('button');

var el2 = dom.create('button');

document.writeln(el1.Id);

document.writeln(el2.Id);

the output will be customNan and customNan.  So the ids are not unique anymore.


The way we would have handled this in C# or Java is by making the counter variable private and not exposing any setter and just use it internally. But as I mentioned earlier, we don't have access modifiers in JavaScript.

The way we can handle this is by creating a module in JavaScript. The basic module pattern involves an immediately invoked function and whatever we return will be publicly accessible outside the function.


var dom = (function(){

    var counter = 0;

    function generateId(){

        return 'custom' + counter++;

    }

    return{

        create: function(tagName){

            var el = document.createElement(tagName); 

            el.Id = generateId();

            return el;

        }       

    }  

}());


If you look at the last line closely, the function is immediately called. If you look at the return statement, we only return one function called create(). Nothing else is exposed from this module.
So now if you create elements like this:

var el1 = dom.create('button');

var el2 = dom.create('button');

document.writeln(el1.Id);

document.writeln(el2.Id);

You will get custom0 and custom1 as the output. The counter variable is now shielded from the global scope, so it acts just like a private variable. It exists only inside the module's closure. So except generateId() and create() no one else can access the counter variable.

Another thing that you can do to make it look cleaner is write create() function before the return statement and return the pointer for the create() function that we created:

var dom = (function(){

    var counter = 0;

    function generateId(){

        return 'custom' + counter++;

    }

    function create(tagName){

        var el = document.createElement(tagName); 

        el.Id = generateId();

        return el;

    }

    return{

        create: create

    }

}());

This further allows us to use the create function anywhere inside the module, if needed and not just the return object.

Conclusion

The Module pattern is a very powerful pattern and helps us to write cleaner code. We can make our variables or functions private and have more control on what we are exposing to the outside world. This pattern has a lot of variations and is quite evolved and I will try to cover the other variations in future posts.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Thursday, September 17, 2015

Dependency Inversion Principle in .NET

In today's blog post, I will be discussing the "D" in SOLID principles i.e. Dependency Inversion Principle (DIP).

Dependency Inversion Principle (DIP)

According to Wikipedia, Dependency Inversion Principle states: 
i) High level modules should not depend on low level modules. Both should depend on abstractions.
ii) Abstractions should not depend on details. Details should depend on abstractions.


Dependency Inversion Principle



Following Dependency Inversion Principle DIP helps you create loose coupling, so that any change in the low level module will not affect the higher level modules. The higher level classes should have loose coupling with lower level classes.

Dependency Inversion Principle helps us to reduce the dependency from one concrete class to another concrete class. By introducing dependency on interfaces instead of classes we get loose coupling which makes our code more supple and easier to change in future.

Let's take a look at an example:

public class Employee

{

   /*

  ;   other properties and methods 

   */        

   public Employee Details(int id)

   {

       private FileLogger fileLogger = new FileLogger();

       fileLogger.Log("Reading Employee " + id);

       Employee employee = db.Employees.Find(id);

       if (employee == null)

       {

        fileLogger.Log("Employee not Found with id = " + id);

        return null;

       }

       fileLogger.Log("Returning Employee with id = " + id);

       return employee;

   }

   //....

}

Here, the Employee class has implicit dependency on FileLogger class. In future, if you have to change the logging mechanism to suppose EmailLogger, imagine the number of places you might have to change the code.

So in order to make them loosely coupled we can create an ILogger interface and make the Employee class use the interface instead of concrete class. 

 public interface ILogger

{

        void Log(string message);

}





public class FileLogger : ILogger

{

        public void Log(string message)

        {

            //implement file logging

        }

}





public class EmailLogger : ILogger

{

        public void Log(string message)

        {

            //implement email logger

        }

}


Please note that, just by using interfaces we can't say that we have applied Dependency Inversion Principle. The higher level objects should own and control the contracts and lower level modules should simply implement them. Higher level modules should not care about how the lower level implementation is done.


public class Employee

{

     private ILogger logger;

     public Employee(ILogger logger)

     {

         this.logger = logger;

     }



     /*

       other properties and methods 

     */



     public Employee Details(int id)

     {

         logger.Log("Reading Employee " + id);

         Employee employee = db.Employees.Find(id);

         if (employee == null)

         {

             logger.Log("Employee not Found with id = " + id);

             return null;

         }

         logger.Log("Returning Employee with id = " + id);

         return employee;

     }

     //....

} 

Please note the constructor of the Employee class with parameter of ILogger. In this way, Employee class explicitly defines that it has dependency on ILogger. Anybody who is consuming the Employee class needs to pass in the concrete implementation of ILogger to be used. So now it's not the responsibility of the Employee class to know what type of logging mechanism is being used.


Three Primary Techniques

Let's gloss over 3 basic techniques used to apply DIP

Constructor Injection

Dependencies are passed in through constructor. This is one of the most common way to implement this. All the dependencies are mentioned as constructor parameters. One of the cons with this is we might not be using all the dependencies all the time, so extra objects in memory and constructor can become too long.

Property Injection

Dependencies are set through property setters. This is more flexible as you can set the properties as needed. The problem is it can lead to classes in inconsistent state. If some calling code doesn't set the required property then we can get erroneous results.

Parameter Injection

Dependencies passed in through method parameter. This is most granular but it can again lead to long list of parameters which is another problem in itself. 



Ioc Container

We can't complete the discussion of Dependency of Inversion Principle without glossing over Ioc containers as well. These manage dependencies and implementations to be used. They automatically resolve dependencies at runtime or start up of the application. For example: Unity, Autofac, Ninject, etc. We will need a separate post on Ioc containers to talk about them at length.

Conclusion

So we saw how Dependency Inversion Principle can be helpful and help us write more loosely coupled code. If we see our classes depending on other concrete classes then we might want to apply some DIP there. So like other SOLID principles this is another principle to keep in mind while coding. This is more useful when we write components for other application to consume. You can apply it at places which you think might be requiring different implementations in future.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)



Thursday, September 10, 2015

Interface Segregation Principle in .NET

In today's post, I will be discussing the "I" in the SOLID principles.

Interface Segregation Principle (ISP)

According to this principle, no client should be forced to implement methods which it does not use. In other words, if you are implementing an interface and you use only a few of the methods out of the interface and don't need other methods, then you are violating the ISP. In such a scenario, the contract needs to be broken down into thin ones i.e. each interface should be more specific.




Interface Segregation Principle


Let's take a look at an example to better understand this.
Suppose you have an interface like this:

public interface IDataStore

{

     void Open();

     void Close();

     Result ExecuteQuery();
}

And, you have a DBStore class which implements the interface like this:

public class DBStore : IDataStore

{

        public void Open()

        {

            //db connection open

        }



        public void Close()

        {

            // db connection close

        }



        public Result ExecuteQuery()

        {

            //execute query code

        }

}


The clients who use the IDataStore interface can connect to the DB and execute queries and close connections. So everything is fine till this point.
Now, suppose you have a new requirement to be able to read file data. You might want to add a new method to your interface like this:

    public interface IDataStore

    {

        void Open();

        void Close();

        Result ExecuteQuery();

        Result ReadFile();

    }


And add a new class FileStore like this:

public class FileStore : IDataStore

{

        public void Open()

        {

            //open file connection

        }



        public void Close()

        {

            //close file connection

        }



        public Result ExecuteQuery()

        {

            throw new NotImplementedException();

        }



        public Result ReadFile()

        {

            //read file 

        }

}


And the DBStore class might look like this:

public class DBStore : IDataStore

{

        public void Open()

        {

            //db connection open

        }



        public void Close()

        {

            // db connection close

        }



        public Result ExecuteQuery()

        {

            //execute query code

        }



        public Result ReadFile()

        {

            throw new NotImplementedException();

        }

}

So we see that FileStore class has to implement ExecuteQuery() method which it doesn't need. Similarly, DBStore class needs to implement the ReadFile() method which it doesn't need. So it's a violation of Interface Segregation Principle.

We can segregate the interfaces into smaller ones like this:

public interface IDataStore

{

        void Open();

        void Close();

}



public interface IDBStore : IDataStore

{

        Result ExecuteQuery();

}



public interface IFileStore : IDataStore

{

        Result ReadFile();

}

And as a result, the FileStore class will look like this:

public class FileStore : IFileStore

{

        public void Open()

        {

            //open file connection

        }



        public void Close()

        {

            //close file connection

        }



        public Result ReadFile()

        {

            //read file 

        }

}


And DBStore class will look like this:

public class DBStore : IDBStore

{

        public void Open()

        {

            //db connection open

        }



        public void Close()

        {

            // db connection close

        }



        public Result ExecuteQuery()

        {

            //execute query code

        }

}

As a result of this, no class needs to implement interface methods which it doesn't need.

Conclusion

This principle is quite practical and makes the code cleaner and easy to use. If you see a bunch of "throw new NotImplementedException()" then probably you are violating the Interface Segregation Principle and need some refactoring. Having smaller cohesive interfaces is what we should strive for.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


(Image Ref: here)

Thursday, September 3, 2015

Liskov Substitution Principle in .NET

In today's blog post, I will be discussing Liskov Substitution principle i.e. "L" in SOLID. I have already discussed Single Responsibility Principle here and Open-Closed Principle here.

Liskov Substitution Principle

According to LSP, the derived classes should be substitutable for their base classes without altering the correctness of the program. In other words, when implementing inheritance in your application, instead of "Is A" relationship, think in terms of "Is Substitutable For" relationship.
Let's look at the famous sqaure-rectangle example to better understand this:

Geometrically, a square is a rectangle. So this may lead us to derive square class from a rectangle class.

public class Rectangle
{
        public virtual int Height { get; set; }
        public virtual int Width { get; set; }

        public int GetArea()
        {
            return Height*Width;
        }
}


public class Square : Rectangle
{
        public override int Height
        {
            get { return base.Height; }
            set { base.Height = base.Width = value; }
        }

        public override int Width
        {
            get { return base.Width; }
            set { base.Height = base.Width = value; }
}


Imagine, we have a test method like this:

 public void TestRectangles()
{
            var r1 = new Rectangle()

            {

                Height = 2,

                Width = 3

            };

            var r2 = new Rectangle()

            {

                Width = 3,

                Height = 2

            };

            var isHeightEqual = r1.Height == r2.Height;

            var isWidthEqual = r1.Width == r2.Width;
}

 So isHeightEqual & isWidthEqual will be true.

However, if we substitute this test example with Square instead of rectangle, we will have:

public void TestRectangles()

{

            var r1 = new Square()

            {

                Height = 2,

                Width = 3

            };

            var r2 = new Square()

            {

                Width = 3,

                Height = 2

            };

            var isHeightEqual = r1.Height == r2.Height;

            var isWidthEqual = r1.Width == r2.Width;

}


So now isHeightEqual & isWidthEqual will be false. As a client, the correctness of my program has been compromised by substituting base class by derived class. So it is a violation of LSP.

One way that you might wanna structure this is by having a Quadrilateral base class and derive Square and Rectangle class from the Quadrilateral class.

public class Rectangle : Quadrilateral
{

        public int Height { get; set; }

        public int Width { get; set; }

        public int GetArea()

        {

            return Height*Width;

        }
}



public class Square : Quadrilateral
{

        public int Size { get; set; }

        public int Area()

        {

            return Size*Size;

        }
}


So a square and rectangle are substitutable for quadrilateral.

Another way might be to not use square class at all. Just use the rectangle class and set height and width equal manually and use it in your code.

Conclusion

This is a simple example to demonstrate the LSP. If our derived class is not perfectly substitutable for base type, then it means that we should start looking at the restructuring of our classes, if possible. Otherwise, it can lead to side effects and may lead to incorrect behavior in the system. Inheritance is a powerful tool in developer's arsenal but it should be used carefully. We should give thought to external behaviors of the entities we are using in inheritance and be able to substitute one for another.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)