Wednesday, October 18, 2017

Observer Design Pattern

Alright lets discuss about one of the Behavioral Pattern - Observer Pattern.

Lets understand where we should use this pattern.

Which problem does this Pattern solve.?
Ans. To understand the pattern we need to understand the problem. This pattern is associated with Publisher and Subscriber model.

Poll Architecture : In this type of architecture the subscriber(s) will continously look  for publisher changes.

The disadvantage with this type of architecture.

1.Even if the Publisher has made no changes the subsciber(s) will continously check to see if there are any changes.

2.The subscriber(s) would have to set a time frame. For example after every 5 min check to see if there are any publisher changes. there could be a publisher change at the 6th min.

3.There could be possible network overhead.

So this Pattern introduces a new type of architecture that is Push Architecture.

Push Architecture - In this type architecture the publisher will tell what is changed and notify the subscriber(s)

The Advantage with this type of architeture.

1.There would be no network overhead.

2.The Subscriber(s) don't have to keep looking for the Publisher changes.

3.There would be no time lapses as publisher will intimate all the subsciber(s)

Definition

Define one to many dependencies/relationships between objects so that when one object changes state then all its dependents are updated/notified automatically.

So lets jump into Weather Station example. This is a hypothetical example.

So we should have a Observable which we define it as Publisher who will notify all the Observers which we define it as Subscriber(s)

Lets create an Observable.It should have - 3 methods  - Attach (Observer) - Detach(Observer) - Notify() to the observers.

Lets create an interface for the same.

public interface IObservable
{
        void Attach(IObserver observer);
        void Detach(IObserver observer);
        void Notify();
}

Attach(Observer) - We need to attach all the observer(s)/subscriber(s) so that the observable/publisher knows to notify its subscibers.

Detach(Observer)  - We can detach the subsciber(s) if not required.

Notify()  - This method is used to notify all the subscribers that there is some changes in the publisher

So in the above we have created a Publisher interface which must and should have these methods.

Lets now create an Observer/Subscriber.

public interface IObserver
{
        void Update();
}

Update() - When the publisher calls Notify Method- It will internally call the update method of each subscribers that will notify the changes to their view.

So lets create  conrete class for the Observable/Publisher - Here we are taking WeatherStation as Publisher.

public class WeatherStation : IObservable
{
        readonly List<IObserver> _observers = new List<IObserver>();
        public int Temperature { get; set; }

        public void Attach(IObserver observer)
        {
            _observers.Add(observer);
        }

        public void Detach(IObserver observer)
        {
            _observers.Remove(observer);
        }

        public void Notify()
        {
            foreach (var observer in _observers)
            {
                observer.Update();
            }
        }

        public int GetTemperature()
        {
            return Temperature;
        }
 }

In the above code you can see we have implemented all the methods in the IObservable and also we have put a new method GetTemperature() - we have implemented this to tell the subscribers that there was a change in  temperature and we notify the subscibers about the same.

So lets create  conrete class for the Observer/Subscriber - Here we are taking PhoneDisplay and ComputerDisplay as subscibers(s). Just an Example(Don't know if they make sense :P)

So lets implement them.

 public class PhoneDisplay : IObserver
 {
        private readonly WeatherStation _weatherStation;
        public PhoneDisplay(WeatherStation weatherStation)
        {
            _weatherStation = weatherStation;
        }

        public void Update()
        {
            Console.WriteLine("Phone Display Temperature"+_weatherStation.GetTemperature());
        }
 }

public class ComputerDisplay : IObserver
{
        private readonly WeatherStation _weatherStation;

        public ComputerDisplay(WeatherStation weatherStation)
        {
            _weatherStation = weatherStation;
        }

        public void Update()
        {
            Console.WriteLine("Computer Display Temperature"+_weatherStation.GetTemperature());
        }
 }

In the above code you could see that there is a concrete class constructor which has a  WeatherStation reference we need this reference so that Subscriber knows to which Publisher it has got attached or referenced to. And also we use the methods of the WeatherStation to notify the changes to subsciber view.

So in the above implementation we see that in the Update method we are using  _weatherStation.GetTemperature() to notify the view about the changes to the temperature.

The Notify method in the weather station is the heart of this pattern.
public void Notify()
{
            foreach (var observer in _observers)
            {
                observer.Update();
            }
}

The notify methods iterate through each observer(s)/subscriber(s) and will notify the user that there is some changes to its state.

Lets see how we attach and notify asubscibers.

class Program
    {
        static void Main(string[] args)
        {
            WeatherStation station = new WeatherStation();
            station.Attach(new ComputerDisplay(station));
            station.Attach(new PhoneDisplay(station));

            station.Temperature = 23;
            station.Notify();

            Console.WriteLine("--------------------------------------------------------");

            station.Temperature = 66;
            station.Notify();
            Console.ReadLine();
        }
   }

In the above code. We are creating an instance of the weatherstation and attaching the subsciber(s) with weather station reference in it. We change the temperature and notify all the subscriber(s)

Happy Coding :) :) :)


Thursday, September 21, 2017

Proxy Design Pattern

Alright lets discuss about one of the structural pattern - Proxy Design Pattern.

Lets first understand the following.

Which Problem does this pattern solve?
Ans.This pattern is predominantly used when we need to control access or resource which is expensive to create it.

Let me explain it breifly.

Suppose there is a Concrete class which has 5 methods. For some reason creating an instance of this class is preety expensive.(When I mean Expensive. Creation of the class instance will take up a lot of memory or resource or may be something else)

So you create a Proxy class. Which will delay the instantiation for a breif period of time.

Below is the Example.

Lets create an Interface ISubject - This interface should and must be inherited by Both Proxy class and Concrete class.

   public interface ISubject
    {
        void Request();

        void Response();
    }

So lets create a Concrete class called - RealSubject which inherits ISubject.

    public class RealSubject : ISubject
    {
        public void Request()
        {
            Console.WriteLine("Called the Real Object");
        }

        public void Response()
        {
            Console.WriteLine("Called the Real Response");
        }
    }

So lets create a Proxy class called - ProxySubject which inherits ISubject -  (We Created this class assuming Creating an Instance of  RealSubject class directly would be more expensive)

If you closely look at the implementation of the ProxySubject - We are doing a Lazy Initialization of the RealSubject object in the Method Implementations -  So this is delay in Initialization that the pattern helps us achieve.

Also we are doing Lazy Initialization so that once we have created a instance of RealSubject we should use it for all the other methods. Else the whole purpose is Proxy Pattern goes for a TOSS and we would end up instantiating each time for each method in the ProxySubject class.

    public class ProxySubject : ISubject
    {
        private RealSubject _subject;

        public void Request()
        {
            //Lazy Initialization
            if (_subject == null)
            {
                _subject = new RealSubject();
            }
            _subject.Request();
        }

        public void Response()
        {
            //Lazy Initialization
            if (_subject == null)
            {
                _subject = new RealSubject();
            }
            _subject.Response();
        }
    }

Finally after all the set up lets instantiate the Proxy class and reap the benefits of the Pattern.

using System;

namespace ProxyDesignPattern
{
    class Program
    {
        static void Main(string[] args)
        {

            //Proxy Pattern - Provides a Surrogacy -or placeholder for controlling access of the subject
            var subject = new ProxySubject();
            subject.Request();
            subject.Response();
            Console.ReadLine();
        }
    }
}

Happy Coding :) :) :)

Thursday, August 24, 2017

Setting up XUnit, Moq, Fluent Assertions, Auto Mapper

We know why do we write Unit Test cases. If you are still not clear you can refer to below link
https://itsmevaibhav007.blogspot.in/2017/01/why-do-we-need-write-unit-test-cases.html where I have briefed about why we need to write unit test cases.

Before we jump into setting up the XUnit, Moq and Fluent Assertions. Let’s first understand what are these in brief

What is XUnit.?
Ans. XUnit is  a Unit test case framework for writing unit test cases against the code that is been written.

Why do we need to choose XUnit. When there are other Unit Test Cases Framework like NUnit, Visual Studio Tools  that are already available in the Market.?
Ans. There are multiple reasons choosing XUnit as Framework. Below are some points.

XUnit is Data Driven Test framework.
Written by the original inventor of NUnit v2
ASP.Net Core framework Unit testing is done by XUnit.

Where can I compare the features of XUnit with Other Frameworks.?
Ans. Here is a Link that will give you clear differences - https://xunit.github.io/docs/comparisons.html

Where can I learn more about XUnit.?
Ans. Here is the link where you can learn more about XUnit- https://github.com/xunit/xunit

What is Moq.?
Ans. Moq is a mocking framework for C#/.NET. It is used in unit testing to isolate your class under test from its dependencies and ensure that the proper methods on the dependent objects are being called.

Why we need to use Moq.?
Ans. Moq framework will help us decouple the dependencies.

For ex say there are multiple Database call that are a part of your code and code intern calls the repository layer. Every time you run a unit test case it would refer to repository which would delay the whole purpose. With Moq we just do that. We Setup the data as if the code is calling the repository and giving the data back.

Where can I learn more about Moq.?
Ans. Here is the link where you can learn more about Moq - https://github.com/moq/moq4

What is Fluent Assertions.?
Ans. With Fluent Assertions, the assertions look beautiful, natural and most importantly, extremely readable.

Why do we need to use Fluent Assertions.?
Ans. By using fluent assertions you could write assert as you say it.

For ex if you want to assert the following the count in the list should be equal to 4.

In Normal case scenario you would write Assert.Equal(employee.count,4);
With Fluent assertion you would write employee.Count.ShouldBeEquivalentTo(4).

Where can I learn more about Fluent Assertions.?
Ans. Here is the link where you can learn more about the Fluent Assertions - http://fluentassertions.com/

What is Auto Mapper.?
Ans. Auto Mapper is a simple little library that will help us to get rid of Old style of mapping one object to another.

Why do we need to use Auto Mapper.?
Ans. If there is situation where you would want to map one object consisting 20 properties with another object consisting 20 more properties the code would look more complicated as you would do old style mapping. One to One. Auto mapper help us get rid of the same.

Where do I learn more about Auto Mapper.?
Ans. Here is the link where you can learn more about the Auto Mapper - https://github.com/AutoMapper/AutoMapper

I have also written how to setup Auto Mapper using reflection you could read more on that in this link - https://itsmevaibhav007.blogspot.in/2016/11/adding-auto-mapper-500-profile.html

Happy Coding :) :) :)

Thursday, January 12, 2017

Why we need to write Unit test cases

Alright so there is been a lot of discussion on writing Unit Test Cases.

First question that a developer asks me is why do we write unit test cases and how does it help us.

My only answer to the question is that It helps you to fail faster than later.

Let me explain you what do I mean by that - So before 3 years I used to have an excel sheet in which I used to put all the conditions and test against those conditions which was very MANUAL in nature.

World was quickly moving forward and I was stuck in the world of manual era.Needed to adopt to moving world and then I started exploring the automotive world that is when I realised the rest of the world writes Unit test cases using frameworks like Ms Test, Nuint

So why do we write Unit test cases - Every developers  job is to ensure that he writes code in a way that it delivers required business value. Essentially the code that a developer writes. Needs to be the best piece of code and a quality one.

So we just refereed to quality keyword above. So what do we mean by that and how do we measure quality.

The answer to this is writing Unit test cases - Tan ta daaa. Wow so do I mean by writing test cases we achieve quality code or build quality product - NO NO NO obviously No. It depends on how you write the code.

You can write bad code and still be able to write unit test cases for the same - Some of my colleagues write Unit test cases without assert and explain me saying that it is at-least covering the code -Management will be happy if there are more unit test cases and code is covered

Alright let come to the point. According to me why do we  write unit test cases.

1.It will help you think like a end user.

2.It will help you have control on the code you write.

3.It will help you have grip on the functionality that you are working on and also helps in delivering the required business functionality.

4.Your thinking capability would grow to another level thus you will get a zeal to write better code.You will refactor the code yourself.

5.Important thing You would understand what SOLID principle mean and how you use them which working in the project.

According to me a piece of code that is non testable is not the best piece of code that is written.

Happy Coding :) :) :)