Friday, December 25, 2015

Generic Delegates in C#

In today's post, we will be discussing generic delegates in C#.

Generic Delegates

Previously, I talked about basics of delegates here. In that example, we used the Employee class for our delegate. The arguments of Employee type were hard-coded and the delegate could not be used with any other data type.

Generic Delegates in C#


With generic delegates we can make the delegate to use a generic type and be flexible with the actual type being used in the delegate.
Let's try to understand this with an example:

Suppose, we have a Person class:

public class Person
{
    public int Id { get; set; }
}


And an Employee class like this:

public class Employee : Person
{
    //Employee properties
}

So for comparing any class objects, let's have a generic delegate type:

public delegate bool AreEqual<T>(T a, T b);

For the actual instance, we can have any class like this:

bool AreSamePerson<T>(T a, T b) where T: Person
{
     ...
}

As we discussed constraints last week here, by having constraints we will be able to use the specific properties of Person class in our method definition.

So let's put them all together to see how it works:

public delegate bool AreEqual<T>(T a, T b);

static void Main(string[] args)
{
      var employeeA = new Employee() {Id = 1};
      var employeeB = new Employee() {Id = 2};
      var employeeC = new Employee() {Id = 1};

      AreEqual<Employee> IsEmployeeSame = 
        new AreEqual<Employee&gt(AreSamePerson<Employee>);

      Console.WriteLine(IsEmployeeSame(employeeA, employeeB));  
         //false
      Console.WriteLine(IsEmployeeSame(employeeA, employeeC));  
         //true

      Console.ReadLine();
}

static bool AreSamePerson<T>(T a, T b) where T: Person
{
     return (a.Id == b.Id);
}


So here we created three employees and compared them. We saw how the generic delegate can take any method (with appropriate signature) and can be used in our code. For delegate instances, we can have different methods (maybe with different constraints) which can be used with the delegate. This way we can generalize our generics and use them.

I can have separate method for IsEmployeeSame and IsPersonSame. If I want to add a new type, for example, Manager deriving from Person and I want it to use AreSamePerson to compare, I can do that or if I want to write a new AreManagerEqual (with Manager type) method, I can also do that.

Conclusion

So in this post, we saw how generic delegates can be useful to us along with an example. The flexibility it provides can help us in different situations.

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 :)


Sunday, December 20, 2015

Constraints on Type Parameters in Generics in C#

In today's blog post, we will be discussing about constraints on type parameters in Generics in C#.

Constraints On Type Parameters

We saw a simplistic use of generics last week here. We saw how generics can help us re-use our code as well as have compile time type safety. In our generics example, we used the .Equals() method which is part of the Object class. The Object class, as we all know, is the ultimate base class of all the classes in .NET framework.

Constraints on Type Parameters in Generics


If we want to restrict the types that we want our Generic class/ method should be able to operate on, we can use constraints. Also, by adding the constraint, we can use the specific behavior/ properties that the constraining type exposes inside our generic method/ class. Constraints are specified using the "where" keyword.

Let's again have our favorite Employee class:

public class Employee
{
    public string Name { get; set; }
    public int EmployeeId { get; set; }
    public decimal Salary { get; set; }
}

Next, let's have a generic method with a constraint of type Employee class:

private static bool AreEqualGeneric<T>(T x, T y) where T:Employee
{
    return (x.EmployeeId == y.EmployeeId) ? true : false;
}

As you can see, by adding the constraint of Employee class we are able to access EmployeeId inside our generic method. Similarly, if there was any public method on the Employee class, we could have accessed that too. Also, we can now use this method only for an object of Employee class (or any derived class of Employee).

Now, let's use our generic method:

static void Main(string[] args)
{
      var employee1 = new Employee()
      {
          EmployeeId = 1,
          Name = "Abhi"
      };
      var employee2 = new Employee()
      {
          EmployeeId = 1,
          Name = "Abhi"
      };

      var isObjRefEqual = employee1.Equals(employee2);
      var isEmployeeIdEqual = 
         AreEqualGeneric(employee1, employee2);
      Console.WriteLine(
       String.Format("isObjRefEqual = {0}", isObjRefEqual));
      Console.WriteLine(
       String.Format("isEmployeeIdEqual = {0}",isEmployeeIdEqual));
      Console.ReadLine();
}

So, here we created 2 employees with same data. First, we compare the object references which turns out to be false because they both are pointing to different objects. When we use the generic method for comparison, we only compare EmployeeIds, so we get a True.

The generics constraints are often useful when we have a base class and multiple derived classes and we want to operate on the properties/ behavior exposed by the base class. We simply add the constraint for base class and then use any of the derived types as parameters to use the generic method/ class.

Conclusion

The constraints are a powerful addition to generics and help us write code that is more specific, as per our needs. By adding the constraints, we tell the compiler that these are the acceptable types for our generic class/ method. And as a result we are able to use that type to write the code specifically for that type.

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, December 10, 2015

Generics in C#

Generics were introduced in C# 2.0 and were the most powerful feature of C# 2 at that time. They allow type and method parameterization in terms of the types they interact with.

Generics

Generics allow classes and methods to have more functionality as compared to what they could do without generics. In order to understand their power, let's take a look at some code without generics. We will then apply generics and see how they can help us.

Suppose, we have a simple method like this:

private static bool AreEqual(int a, int b)
{
     return a == b;
}

We can use this method in our code anywhere:

var x = AreEqual(10, 11);

It works fine as long as the application is limited to use only integers. Suppose, we want to use another type, for e.g. string for similar method. In order to do that, we will have two options (pre C# 2.0):
i) Create a new method AreEqual() which takes string arguments,
ii) Change AreEqual() method to have parameters of type object.

First solution will lead to code duplication for each and every newly added type.
Second solution will lead to casting of the objects each and every time, which might lead to performance issues. Also, by casting to object, we loose compile time type safety which may lead to run-time exceptions.

So now let's take a look at how we can simplify it using generics:

private static bool AreEqualGeneric<T>(T a, T b)
{
     return a.Equals(b);
}

So now we can use the generic method like this:
var y = AreEqualGeneric<int>(11, 11);

var z = AreEqualGeneric<string>("A", "B");

As you can see we are able to use the same method with different parameter types. So now we are able to write generic code one-time as well as have compile time type safety.

Conclusion

We saw how generics help us decouple logic from data type. In future posts, I will be covering some more on generics in C#.
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, December 3, 2015

Value vs Reference Types in C#

In today's blog post, I will be discussing the difference between value and reference types. There are certain misconceptions among people about the differences between the two.

Whenever there is a discussion on value vs reference types in C#, there are two user defined data types that come to mind: structs and classes. A struct is a value type and a class is a reference type. Let's understand their differences one by one.

Value Types

Suppose, we have a struct like this:

struct S
{
    private int x;
    private int y;
    //code...
}

When we create an instance of this struct, the memory is allocated on the stack and only one space is created in the memory for the instance.

S instance = new S();

The space for instance gets allocated on the stack.
If we do,

S instance2 = instance;

A new instance called instance2 is created (on stack) and is completely independent of the instance variable's value.
So when we pass a value type as a method parameter, it comes as a complete separate copy. Any changes to it are not reflected back in the caller code.

Reference Types

Suppose, we have a class like this:

class C
{
    private int x;
    private int y;
    //code...
}

When we create an instance of this class, 2 memory allocations happen: the variable is stored on the stack and object is stored on the heap.

C classInstance = new C();

So here classInstance variable is stored on stack and the actual object is stored on the heap. The classInstance variable simply refers to the object on the heap.

If we do,

C classInstance2 = classInstance;

classInstance2 is a new variable (created on stack) and it points to the same object (on heap) as referred by classInstance variable. So if we make any changes in the object using classInstance2 variable, the changes are reflected in classInstance variable's object too (because it's same). If I change the value of classInstance2.x, then classInstance.x is also changed. However, if I update the classInstance2 to refer to something else, for example if we set,

classInstance2= null;

It won't affect classInstance variable because we simply update the classInstance2 variable to point to a null reference. So when we pass objects like this to methods, the changes made to the object by the callee method are reflected back in the caller method. However, if we update the reference itself, that's not reflected back.

Ref Keyword

If in case, we want to update the reference too, we can use the ref keyword.

void Method1(ref C classInstance3)
{
    classInstance3 = null;
}

Method1(ref classInstance);

In this scenario, classInstance will be set to null by the callee method.

Conclusion

So we saw the differences between value and reference types in this article. We also saw that stack stores reference portion of reference-typed local variables and parameters and value typed local variables which are not part of a reference type. And heap stores content of reference type objects and anything inside a reference type object. So a generic statement like all value types are stored on stack might not be correct all the time as value types which are inside reference type objects are stored on heap.

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, November 26, 2015

Multicast Delegates in C#

In today's article we will be discussing multicast delegates in C# with example.

Multicast Delegates

As we discussed last week about delegates here, a delegate points to a function. We saw an example of a delegate pointing to a function and how we can use it. However, when using delegates we are not limited to pointing the delegate instance to only one method. With one delegate call, we can invoke multiple methods. The multicast delegate keeps a list of assigned delegates and calls them one by one when invoked.

multicast delegates in C#
Multicast Delegates in C#


Let's look at an example.
Suppose, we have an Employee class like this:

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime PositionChangeDate { get; set; }
    public decimal Salary { get; set;}
}

And here is the multicast delegate for employee promotion:

public delegate void CustomDel(Employee employee);
static void Main(string[] args)
{
       var employees = new List<Employee>()
       {
             new Employee(){Id = 1, Name = "Abhi", Salary = 10},
             new Employee(){Id = 2, Name = "John", Salary = 20}
        };

        CustomDel SalaryRaiseDel, PositionDateDel, 
                  EmployeePromoteMulticastDelegate;
        SalaryRaiseDel = new CustomDel(EmployeeSalaryRaise);
        PositionDateDel = new CustomDel(PostionDateUpdate);
      
        //multiple delegates assigned
        EmployeePromoteMulticastDelegate = PositionDateDel 
                                         + SalaryRaiseDel;

        foreach (var emp in employees)
        {
            EmployeePromoteMulticastDelegate(emp);
            {
                Console.WriteLine("Id = " + emp.Id);
                Console.WriteLine("Name = " + emp.Name);
                Console.WriteLine("Salary = " + emp.Salary);
            }
        }

        Console.ReadLine();
   }
    

//set position change date to current time
private static void PostionDateUpdate(Employee employee)
{
     employee.PositionChangeDate = DateTime.Now;
}

//raise employee salary by 10%
private static void EmployeeSalaryRaise(Employee employee)
{
     employee.Salary += employee.Salary + employee.Salary 
          * (decimal) 0.1;
}

So here I created a multicast delegate called EmployeePromoteMulticastDelegate. This delegate is assigned 2 other delegates viz. SalaryRaiseDel & PositionDateDel. So when we call the EmployeePromoteMulticastDelegate with Employee parameter, it calls EmployeeSalaryRaise() and PostionDateUpdate() methods. So with one call we were able to call 2 methods.

Any delegate when assigned multiple methods to invoke becomes multicast delegate. There is no special syntax for multicast delegates.

Conclusion

Multicast delegates are a powerful feature of C# and are used to apply publish subscribe pattern. By invoking an event, we can call multiple methods who have subscribed to the event.

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, November 19, 2015

Delegates in C#

In today's blog post, we will be discussing delegates in C#.

Delegates

Simply put, a delegate is a type safe function pointer. It defines the signature of the method that can be used. The delegate can point to any method as long as the signature of the method is the same. The signature here includes the parameter types and return types.

delegates in C#

Let's take a look at a simple example of delegates and see how they can be useful. Let's have our favorite Employee class like this:

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime StartDate { get; set; }
}
Suppose, we want to find out all the employees who can be promoted. So we might write our code something like this:

static bool IsEmployeePromotable(Employee employee) 
{
   if (DateTime.Now.Year - employee.StartDate.Year > 5)
         return true;

    return false;
}

static void Main(string[] args)
{
    var employees = new List<Employee>()
    {
        new Employee(){Id = 1, Name = "Abhi", StartDate = new DateTime(2010,1,1)},
        new Employee(){Id = 2, Name = "John", StartDate = new DateTime(2005,1,1)}
    };

   foreach (var emp in employees) 
   {
        if (IsEmployeePromotable(emp))
       {
          Console.WriteLine("Id = " + emp.Id);
          Console.WriteLine("Name = " + emp.Name);
       }
   }
    Console.ReadLine();
}

So here the program prints all the employees who has more than 5 years of experience in the company. So this looks fine and short.
Suppose, we have some more requirements that want to change the promotion criteria. This will lead us to change the existing code. For any new criteria to be added we will have to change the existing code again and again.  Delegates can help us here as we can inject the promotion criteria on the fly. Let's see how we can do that using delegates:

public delegate bool PromotableEmployee(Employee employee);
static void Main(string[] args)
{
    var employees = new List<Employee>()
    {
        new Employee(){Id = 1, Name = "Abhi", StartDate = new DateTime(2010,1,1)},
        new Employee(){Id = 2, Name = "John", StartDate = new DateTime(2005,1,1)}
    };
    PromotableEmployee IsEmployeePromotable = new PromotableEmployee(IsEmployeeFiveYearsOld);
    foreach (var emp in employees) 
    {
        if (IsEmployeePromotable(emp))
        {
            Console.WriteLine("Id = " + emp.Id);
            Console.WriteLine("Name = " + emp.Name);
        }
    }
    Console.ReadLine();
}

static bool IsEmployeeFiveYearsOld(Employee employee)
{
    if (DateTime.Now.Year - employee.StartDate.Year > 5)
        return true;
    return false;
}

So here I created a delegate type called PromotableEmployee. This type can have any method assigned to it as long as it conforms to the signature. We have this method called IsEmployeeFiveYearsOld() which conforms to the signature. When we created the delegate instance called IsEmployeePromotable which uses IsEmployeeFiveYearsOld() method. And then we use the delegate instance in our program. When we create the delegate instance, we can assign any method to it as long as it conforms to the signature. That's the power of the delegates. 
So I can create any new PromotionCriteria and add it to the code base. Then we can inject that method on the fly.

Conclusion

Delegates are powerful feature of C# and have improved a lot over different versions of C#. I will be discussing multicast delegates in the next post which will show how delegates can be more useful to us.
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, November 12, 2015

Async Await in C#

In today's blog post, I will be talking about how to do asynchronous programming in C# using async await keywords.

ASYNC AWAIT

Earlier (before C# 5), writing asynchronous code used to be difficult and bug-prone. With C# 5 came async await which made writing asynchronous code lot easier.


Async Await C#



Let's take a look at a simple example of how to do this.
In order to demonstrate this, I created a small web form application which looks like this:


Web Form .NET Async Await C#


The code behind looks like this:


public Form1()
{
    InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
    var result = SlowMehtod("Abhi");
    label1.Text = result;
}

private string SlowMehtod(string str)
{
    Thread.Sleep(2000);
    return "Welcome " + str;
}



So when I click the button, it updates the label1 text to "Welcome Abhi". However, as you can see I added a Thread Sleep statement to add a delay of 2 seconds. The reason why I did this is to make the method slow (who does that!). In your code, you might have some method which accesses resource over the web or some database or due to some other reason, its slow. I just simulated the slow behavior. So when I click the button, my form freezes for 2 seconds and then it shows "Welcome Abhi".

If we are blocking the UI thread, we are basically freezing the application and making the user experience not pleasant. The user might think that application is frozen and might just kill the process. So we should avoid blocking the UI thread.

By wring asynchronous code, we can put the slow method to execute in parallel. Let's take a look at how we can do that here:

private void button1_Click(object sender, EventArgs e)
{
    CallSlowMethodAsync("Jain");
    label1.Text = "Waiting...";
}

private async void CallSlowMethodAsync(string str)
{
    var result = await SlowMehtodAsync("Jain");
    label1.Text = result;
}

private Task<string> SlowMehtodAsync(string str)
{
    return Task.Factory.StartNew(() => SlowMehtod(str));
}

private string SlowMehtod(string str)
{
    Thread.Sleep(2000);
    return "Welcome " + str;
}

For writing async code, we simply created a new method with async keyword. Inside async method, there is await which marks the method that will be executed in parallel. The await calls the SlowMethodAsync which return a Task<string>.  By convention the name of the async method ends with an "Async" suffix. The return type of async method can be:

  1. Task<TResult> - if method is returning something of type TResult.
  2. Task - if method has no return statement or empty return statement.
  3. Void - if it's async event event handler.

So now when I run this application, and I click the button, the label text changes to "Waiting..." right away. Then after 2 seconds, it updates to "Welcome Jain". During the time the SlowMethod() is running, the UI doesn't freeze anymore as it's running asynchronously :)

Web Form .NET Async Await C#


Conclusion

C# 5 makes it very easy to write asynchronous code and we should use this feature when we have any slow running code threatening our user experience ;)

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, November 5, 2015

JavaScript Generators

In today's blog post I will be discussing what JavaScript generators are and how they can be useful. Generators are part of ES6 and are truly a game changer.

Generators

Usually when we execute any functions, they run till the end (or first return statement). We cannot pause them in between and do something else.
The ES6 generators are special types of functions which can be paused. We can pause them, re-run them, pause them again and re-run them and so on.

Javascript Generators


A "function*" is used to represent a generator function and "yield" keyword marks the pauses in the generator. Let's take a look at an example:

function *foo() {
    yield 'a';
    yield 'b';
    yield 'c';
}

In order to use it, we simply call the next() function on the generator like this:

var func = foo();
console.log(func.next());  // Object {value: "a", done: false}

This return the first yield value i.e. 'a'. Next time, we call func.next(), we get this:

console.log(func.next());  // Object {value: "b", done: false}

So you can see how the function execution gets paused on each yield. And how it re-runs on each next() call.
If we execute it more, we get:

console.log(func.next()); // Object {value: "c", done: false}

console.log(func.next()); 
// Object {value: undefined, done: true}

So once it reaches the end of the generator function, we get the value as undefined and done as true. Once a generator function is done, it will keep returning the same values of undefined and true, no matter how many times we call the next() function on it afterwards.

Now, let's take a look at how we can do two-way communication using generators. Whatever we pass in the yield as argument, we get it back as the Object's value.

function *foo(a) {
    var b = 3 * (yield (a + 2));
    console.log(b);                         //24
    var c = yield (b / 2);
    console.log(c);                         //13
    return (a + b + c);
}
var func = foo(6);
console.log(func.next());   // Object {value: 8, done: false}
console.log(func.next(8));  // Object {value: 12, done: false}
console.log(func.next(13)); // Object {value: 43, done: false}


And if we want to pass anything to the generator function, we pass it as argument to the next() call.
So in the example above when we call foo() function, we pass 6 as argument. That's the value of "a". Then we call func.next() - that returns (6+2=) 8 as the value. The generator is paused at the first yield. Then we call func.next() second time with argument of 8. So the value of b is assigned as (8*3=) 24. So we passed in the value 8 into the generator function and that gets used inside the function.
Then, we called func.next() with argument 13 and that gets assigned to c. Then the last value is returned as  (6+24+13=) 43.

Why useful?

So the reason why these pausable functions can be useful is for asynchronous programming. We can do "yield" followed by asynchronous call. This will fetch the result of that asynchronous call. And whenever we are ready for the next call, we can simply call the next() function and get the result of the next asynchronous call. We can also pass in any arguments we like to the next() call which can be used in the asynchronous request we are making. 

function * () {
    var a = yield async1();
    var b = yield async2(a),
    var c = yield async3(b);
    console.log(a, b, c);
};


Conclusion

JavaScript Generators are a great way to write asynchronous code. We will have to write more and more of asynchronous code as the time progresses. Nesting asynchronous calls and callbacks makes our code look dirty and difficult to debug. With generators, not only the code will look better but will also be easier to debug.

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, October 29, 2015

JavaScript Promises

In today's blog post we will discuss what promises are in JavaScript and how they are useful. In my last week's blog post here, I discussed about callback functions and the callback hell problem. Today, we will see how promises can help us tackle the callback hell problem.

Promise

Promise represents the eventual result of an asynchronous operation. Promise is an object which represents a handle that listens to the results of an async operation. In other words, Promise promises to alert you when async operation is done and return the results.



Promises in JavaScript


As we know, in the nested callbacks, it's really difficult to manage and debug the code and it gets worse with more nesting. For example, if you have something like this:

function load(){
  var connection = new connection();
  connection.loadBook(function(err, connection){
      connection.loadChapter(function(err, connection){
          connection.loadPages(err, function(err, collection){
          });
      });
  }); 
}

You can see this is getting ugly and will be difficult to manage. Now, on top of it, if you add error handling to each and every call, the function may look something like this:

function load(){
   var connection = new connection();
   try
   {
       connection.loadBook(function(err, connection) 
       {
           try
           {
               connection.loadChapter(function
                    (err, connection) 
               {
                   try
                   {
                     connection.loadPages(err, 
                 function(err, collection) 
                       {
                       });
                   }
                   catch(ex)
                   {
                       //handle exception for load chapter
                   }
               });
           }
           catch(ex)
           {
               //handle exception for load chapter
           }
       });
   } 
   catch(ex)
   {
       //handle exception for load book
   } 
}


You can see the point, it's even more ugly and difficult to manage. This is called callback hell problem.

Promises

Promises are used to solve the callback hell problem. Promises are part of libraries like jquery, Q, RSVP and are also part of ES6. Let's understand the basics first.

A promise has 3 different states:
i)   PENDING       - not done yet
ii)  FULFILLED   - done
iii) REJECTED     - error
There is also a 4th stage i.e. SETTLED which means that promise is either Fulfilled or Rejected. 

When we create a promise, we need to pass in 2 different methods:
i)  resolve - method that's called on successful completion of promise
ii) reject   -  method that's called on error


var promise = new Promise(function(resolve, reject) {
  if (1==1) {   //we can decide any condition here
    resolve("Promise worked!");
  }
  else {
    reject(Error("Promise failed"));
  }
});
promise.then(function(result) {
  console.log(result); 
}, function(err) {
  console.log(err); 
});

When we invoke the promise using "then", we pass in the functions that need to be used for resolve and reject.

So the example code we saw with callback hell problem above, might look something like this with promises:

function load()
{
    var connection = new connection();
    connection.getbook().then(function(book){
       return getChapter(book.id);
    }).then(function(chapter){
       return getPages(chapter.id); 
    }).then(undefined, function(error){
       //handle error
    })
}

As you can see the code looks so much better with promises. The error handling has been simplified too. The last "then" in the code above uses only reject function, so we passed undefined for resolve function there and only reject function has the value.

Conclusion

Promises help us write asynchronous code in a much cleaner and efficient way. As asynchronous code is becoming more and more prevalent, promises are being used more often.

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, October 22, 2015

Callbacks in Javascript

In today's blog post, I will be talking about what callback functions are and their advantages and disadvantages in JavaScript. Callback is a functional programming technique which allows the use of functions as arguments.

Callback Functions

Simply stated, a callback is a function that is passed as an argument to another function. For example,

setTimeout(function() {
    console.log('abhi');
}, 2000);                     //prints 'abhi' after 2 seconds

In the above example, we used a function which just logs one word to the console. The function passed to setTimeout function is the callback function. setTimeout is an inbuilt function in JavaScript which executes the argument function after specified number of milliseconds.
We can pass callbacks either anonymously (as above example) or as a named function (as shown below).




setTimeout(logger, 2000);
var logger = function() {
    console.log('abhi');  //prints 'abhi' after 2 seconds
} 

This code sample does the same thing as one above, except this time named function is used.

Writing own callbacks

We can easily write our own callbacks. Here, we created a simple objLogger function which prints all the object's own properties and their corresponding values. This objLogger function is then used as a callback. The changeName function simply executes the callback function and passes the object to it. The objLogger function prints the property name and it's value.  

var objLogger = function(obj){
  for (var item in obj){
  if(obj.hasOwnProperty(item)){
     console.log(item + ': ' + obj[item]);
    }
  }
}

var changeName = function(obj, callback){
  obj.name = 'abhi2';
  callback(obj);           //callback function execution
}

var obj1 = {name: 'abhi'};
changeName(obj1, objLogger);       //name: abhi2

Another good practice when using callbacks is to check their type before executing them.

if( typeof callback === 'function'){
    callback(obj); 
}


Synchronous & Asynchronous Callbacks

The setTimeout examples that we saw earlier were callbacks which are executed asynchronously. The logger function that we just saw was executed synchronously. So we can use them in both ways in similar way.
The callbacks are used more often in the asynchronous context (for example, Node.js). However, please note, just by using callbacks our code doesn't automatically become asynchronous. If we are writing our own callbacks, we can use them either synchronously or asynchronously.

Callback Hell Problem

When we write a lot of nested callbacks the code looks unwieldy and difficult to understand. This problem of nested callbacks is known as callback hell problem.

Suppose, we have an example where we load a book first, then we load it's chapters and then we load pages and so on... We want to do that asynchronously and on success of previous one, the next call goes out. The code may look something like this:

var connection = new connection();
connection.loadBook(function(err, connection) {
    connection.loadChapter(function(err, connection) {
        connection.loadPages(err, function(err, collection) {
        });
    });
}); 

As you can see the code has started looking bad with multiple nested callbacks. In case of complex code, this might go several layers. Such a code is not only difficult to read but also to debug.
One way to combat this is to always use named functions instead of anonymous functions. That will make it somewhat easier to read. I will be discussing more on how to combat this callback hell problem in my next week's blog post.

Conclusion

Callbacks are used very commonly in JavaScript code. A proper understanding of these helps us write better code and understand the pre-written code better. These are used extensively in various JavaScript libraries and frameworks.



Thursday, October 15, 2015

Function Invocation Patterns in Javascript

In today's blog post, I will be discussing the four different ways in which functions can be invoked in JavaScript.
Other than the declared parameters, every function receives two additional parameters: "this" and "arguments". In object oriented programming, the "this" parameter is very important and we will see how "this" is set in each pattern in this post.


Function Invocation Patterns in JavaScript



Method Invocation

When a function is a property of an object, it is called a "method".  This is the pattern of invoking a function that is part of an object.

var obj = {
    value: 0,
    increment: function(){
            this.value++; 
     }
} 
obj.increment();
console.log(obj.value); 

increment function is part of object obj. The object that is used to invoke the function constitutes "this" in case of method invocation pattern. JavaScript binds "this" at execution time a.k.a. late binding.

Function Invocation

When a function is not a property of an object and is simply invoked using (), that's function invocation pattern.

var sum = add(2,7);

When a function is invoked using this pattern, "this" is associated to the global object. This behavior can lead to confusing errors. Let's take a look at an example:

var name = 'abhi';
var person = {
    name: 'jain',
    printName: function(){
        var helper = function(){
             console.log(this.name)
        }
        helper();   //function invocation pattern           
    }
}

person.printName();         //abhi


Since printName function was defined inside person object, I was expecting the printName function to use the name property from person object. But since printName uses a helper function and the helper function is invoked using function invocation pattern, it associates "this" to global object. As a result, global variable's value is printed.

An object's method cannot use an inner function to help do it's work because the inner function does not have access to the object. The "this" for the inner function is bound to wrong value.
In order to allow inner function to access the object, we can assign the value of "this" to another variable and use that variable in the inner function. Conventionally, that variable is called "that". 

var name = 'abhi';
var person = {
    name: 'jain',
    printName: function(){
        var that = this;
        var helper = function(){
             console.log(that.name)
        }
        helper();   //function invocation pattern          
    }
}
person.printName();    //jain



Constructor Invocation

When we invoke a function using new keyword, it's called constructor invocation pattern.
In this case, a new object is created with a hidden link to the value of the function's prototype member and "this" will be bound to that new object.
JavaScript's prototypal inheritance nature is explained here. JavaScript offers object making syntax similar to classical languages like Java, C# etc with new keyword. This obscures the language's true prototypal nature. 

function Person(type){
  this.type = type;
}
var employee = new Person('employee');

console.log(employee.type);         //employee

Conventionally, the functions to be used with this pattern are kept in variables with capitalized name. 
In this example, the function Person when called with new keyword, returns an object with one property called type. The value of type property is set to the argument passed. 

If a function is intended to be used with this pattern, and somewhere in the code, new keyword is missing, it can lead to difficult to find errors. So we should be careful of the naming convention as that is the only savior.

Apply Invocation

The apply method is defined on every function. We can call the function using this apply method. By using the apply method, we can pass the arguments as array and explicitly choose the value of "this".

var add = function(num1, num2) {
        return num1+num2;
}

array = [5,4];

add.apply(null,array);    //9

So here we passed the arguments as array. 
In the next sample, let's see how to set the "this" object for the function:

var showName = function(){
    console.log(this.name);
}

var obj = {
  name: "Abhi"
}

showName(obj);       //abhi 

If we look inside the add method, we can see the apply and call method:

Call and Apply in function
Similarly, we can use add function using call method as well. Call method is similar to apply method except instead of having arguments as array, we provide list of arguments as seen in the example below:

var add = function(num1, num2) {
        return num1+num2;
}

add.call(null,5,4);      //9

Conclusion

It is important to understand these different patterns because it's very confusing and can lead to hard to find bugs in our JavaScript code. JavaScript has it's own peculiarities and better understanding of these can help us write better code and avoid the bad parts of the language.

Ref: Javascript: The good parts by Douglas Crockford

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, October 8, 2015

Prototypal Inheritance in Javascript

In today's blog post I will be discussing the prototypal inheritance in JavaScript.

Prototypal Inheritance in JavaScript

In most languages (like Java, C#, etc) inheritance is class based. We derive one class from another to reuse the pre-written code and establish hierarchy of different types so we can use them easily throughout our application.


Prototypal Inheritance in Javascript

JavaScript does not have concept of classes. The object themselves carry their data and capabilities. The lineage of the object doesn't matter, only what they can do. JavaScript is a prototypal language i.e. objects inherit from one another.

Let's understand this one by one with examples. The first thing that we need to understand is that functions in JavaScript are objects. So if we have a function named person, we can add any property to it, e.g. type.
 
function person(){}
person.type = 'employee';
console.log(person.type);    //employee

Next, I want the person to be of different types. So I add a type property and return that object.

function Person(type){
  this.type = type;
}

var employee = new Person('employee');
var manager = new Person('manager');

console.log(employee.type);      //employee
console.log(manager.type);        //manager

Please note that this time the function name is capitalized. It's just a convention followed by JavaScript developers that this function needs to be used with new keyword to create instance of Person (I will be writing blog post on constructor invocation next week). So I added this property called type which we pass when we create the object. So we passed 'employee' and 'manager' as the type in the constructor. Invoking new Person('employee') returns the "this" object with type property set to the parameter value.


Next, I want to add smile method to the Person. So you might think by adding it to Person should suffice like this:

function Person(type){
    this.type = type;
}

Person.smile = function(){
    console.log("Smile");
}

var employee = new Person('employee');

console.log(employee.smile());       //employee.smile is not a function
console.log(employee.__proto__);  //contains no smile method   
console.log(Person.smile());           //Smile


As you can see by adding it to Person object, we don't automatically add it to the instances of the Person object. The smile method is available on Person but not on employee. The reason being when we call new Person('employee'), we return the "this" object which has only one property called type defined. Since Person.prototype does not have smile method and employee.__proto__ is created from Person.prototype we will find that there is no smile method in employee.__proto__ as well.

The way Javascript works is, when we look for a property or a method on an object, it's looked up in the following order:

1. employee object has smile method()
2. Employee.prototype has smile method() defined explicitly
3. Person prototype has smile method. Since employee prototype is created using Person prototype object (inheritance).


So, one simple way of adding the smile method to returned objects can be this:

function Person(type){
   this.type = type;
   this.smile = function(){
    console.log("Smile");
    }
}

var employee = new Person('employee');
var manager = new Person('manager');

console.log(employee.smile());          //Smile
console.log(manager.smile());            //Smile


Another way of accomplishing the same thing (which we are more interested in) can be by adding it to the Person's prototype like this:

function Person(type){
   this.type = type;
}

var employee = new Person('employee');
var manager = new Person('manager');

Person.prototype.smile = function(){
    console.log("Smile");
}


console.log(employee.smile());      //Smile
console.log(employee.__proto__); //contains smile method
console.log(manager.smile());        //Smile

Now employee and manager have smile method. This time, the smile method was defined in Person prototype which sets the employee and manager's prototype. Voila, this way we were able to inherit using prototype. 

Now, let's just use the type property inside the smile method to show which type of employee is calling the smile method:

function Person(type){
  this.type = type;
}

var employee = new Person('employee');
var manager = new Person('manager');

Person.prototype.smile = function(){
    console.log("This is "+ this.type +  " smile");
}

console.log(employee.smile());   //This is employee smile
console.log(manager.smile());     //This is manager smile

Next, to further improve, if we want to have separate function for Employee, we can do like this:

function Person(type){
  this.type = type;
}

Person.prototype.smile = function(){
    console.log("This is "+ this.type +  " smile");
}

function Employee(){
    //calling constructor and passing "employee" as type
    Person.call(this, 'employee');
}

Employee.prototype = Object.create(Person.prototype);

var employee = new Employee();

console.log(employee.smile());     //Smile

Here, we created Employee function which returns a Person object and passes "employee" as type. Here, we set the Employee prototype explicitly to create an object using Person prototype. As a result, we inherit everything from Person's prototype. This is what happened internally in the previous examples we saw where smile() was inherited from Person's prototype.

Conclusion

The prototypal inheritance is a powerful concept and it's very different from other common languages like C# and Java. That is why its very important to understand this properly.
So in this article we saw how to implement inheritance in JavaScript and understood the underlying concept.

Image Ref: here

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, October 1, 2015

Augmenting Types in Javascript

In today's post, I will be discussing the advantages of augmenting types and how to accomplish that in Javascript.

Augmenting Object

Augmenting is the mechanism of extending characteristics of a thing by adding new things. That characteristic is then available to all the instances of that thing.
So in case of an object, by adding a method or property to Object's prototype, we make it available to all objects.

For example,

var person = {

   "FirstName" : "Abhi",

   "LastName": "Jain"

}

console.log(person.FirstName);

console.log(person.email);            //undefined

As you can see in the example, the email property was not available for the person object. By adding email to Object's prototype, we make it available to all objects. This is called augmenting the Object.prototype.

Object.prototype.email= "xyz";

console.log(person.email);           //xyz 

Similarly, we can augment Object.prototype to add new methods which will become available to all the objects. 

Augmenting Types

In the same way, we can augment functions, booleans, arrays, strings, numbers and regular expressions. This can come in handy, when we need to implement some functionality to be used across the board. For example, we can add integer function to Number to return the integer part of the number. We can do it like this:

Number.prototype.integer = function(){

      return Math[this < 0 ? 'ceil' : 'floor'](this);

}

console.log((-11 / 3).integer());

Similarly, we can add trim method to String which will simply remove the extra spaces.

String.prototype.trim = function(){

     return this.replace(/^\s+|\s+$/g, '');

}

console.log("  Abhi  ".trim());       //"Abhi"

Now the trim method will be available for all strings.

Caveat

Modifying Object.prototype (and others like Number.prototype, etc) is usually considered evil and frowned upon. The reason being namespace collision. Suppose, one library adds Map method to Object with some implementation and another library also adds Map method with another implementation, so the latter one overrides the former one. This might lead to broken functionality and hard to maintain code.

Another problem is that for-in statement interacts badly with prototypes. When we do a for in loop like this: 

for (var key in person)

{

     console.log(key);   

}

we get FirstName, LastName and Email. Although Email is not person object's own property, it still pops up in the loop. One way to mitigate this is to use hasOwnProperty like this:

for (var key in person)
{

    if(person.hasOwnProperty(key))

    {

        console.log(key);

    }

} 

This will show only FirstName and LastName.

Conclusion

In this post, we saw one of the powerful features of Javascript on how to augment types and how it can be useful to us. We can use this feature to help us add generic functionality which might be needed at multiple places. Some of these things are not that relevant anymore as there are lots of Javascript libraries which give us most of the functionalities we need. However, if we need something custom for ourselves these can come in handy.
Also, such native augmentation should be used when you know that you are working in a controlled environment.

Ref: Javascript - The Good Parts by Douglas Crockford

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 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 :)