Monday, December 16, 2013

Wrap your original Exception in C#

Exception handling mechanism is very essential in every application. A good coding stricture does not leave a single piece of code which might give trouble in application. That’s fine, C# has given facility to handle Exception using try-catch block.
Now as a developer we know there are thousand types of Exception which might occur in application and we know their technical meaning. But how one legitimate user will know their meaning? For example, there is one SMTP related Exception in your application due to down of the mail server. If we show the message something like that to user

“There is SMTP error and port 25 is not open” .

I am sure that from next day the user will never come back in your application because they don’t want to face those technical jargons in next time. Ha..Ha..Yes, this is the real scenario. So, the solution is, we have to wrap our original exception and we have to show a polite message to user like.

“We are unable to send your mail. Please try after some moment.”

User will think that, Oh, the application knows how to behave, at least. Cool, we have learned the necessity of Wrapping actual exception which is very much developer friendly and by wrap it with another exception we will make it user friendly.


At first we will implement one exception example without wrapping it with another exception object and have a look, how technical message it’s throwing to user interface part.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    public class TestClass
    {
        public void ActualException()
        {
            try
            {
                throw new StackOverflowException();
            }
            catch(Exception ex)
            {
                throw;
            }
        }
        public void BubbledException()
        {
            try
            {
                ActualException();
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                TestClass t = new TestClass();
                t.BubbledException();
                Console.ReadLine();

            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }

        }
    }
}


Ok, It’s throwing “Stack overflow” exception but how many of our user does know the meaning of stack? If the user is not another developer.


Now, in this example we will wrap the actual exception with our custom exception class. We have developer one “customException” class which is derived from base “Exception” class. Within custom class we have implemented six constructors which will take different parameter flavor and those will help to manipulate different kind of wrapper object.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    public class CustomException : Exception
    {
        public CustomException()
            : base() { }

        public CustomException(string message)
            : base(message) { }

        public CustomException(string format, params object[] args)
            : base(string.Format(format, args)) { }

        public CustomException(string message, Exception innerException)
            : base(message, innerException) { }

        public CustomException(string format, Exception innerException, params object[] args)
            : base(string.Format(format, args), innerException) { }

        protected CustomException(SerializationInfo info, StreamingContext context)
            : base(info, context) { }
    }

    public class TestClass
    {
        public void ActualException()
        {
            try
            {
                throw new StackOverflowException();
            }
            catch(Exception ex)
            {
                throw;
            }
        }
        public void BubbledException()
        {
            try
            {
                ActualException();
            }
            catch(Exception ex)
            {
           throw new CustomException("System is failure to process the request", ex);
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                TestClass t = new TestClass();
                t.BubbledException();
                Console.ReadLine();

            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message + "\n");
                Console.WriteLine(ex.InnerException + "\n");
                Console.ReadLine();
            }

        }
    }
}

Within yellow mark we are showing the custom message thrown by “StackOverflowException”. The message is pretty polite

“System is failure to process the request”.

But the important task is to log the actual exception for developer’s own purpose. We can do it by accessing InnerException property of Exception Object.
Within green box we are representing the actual Exception.

Saturday, December 14, 2013

Understand Constructor Injection in Dependency Injection.

We know that Dependency Injection is software design pattern that allow us to implement loosely couple architecture. The term “loosely couple” carries deep meaning. Before going to discussing of Constructor injection I would like to clarify few important concepts.

What is coupling?


The term coupling represents the relationship between two objects. That means, when two and more object will very much dependent on each other we will say that they are tightly coupled.
Say for example; think about selection process in organization. One has submitted his CV to organization. If his CV gets shortlist then he will get interview call and if he crack interview then we will get offer latter. So, here one process like getting call for interview very much dependent on CV short listing process and getting offer letter process is dependent on his interview process. So, all processes are tightly coupled to each other.
Ok, if we represent this scenario in general manner, process x is dependent on process y and again process y is dependent on process z and in other way process x is dependent on process z that is called transitive dependency.
Couplings are two types in nature

Tight Coupling:- Which is not expected in application in the view point of good design pattern.
Loose Coupling:- Which everyone expects from a good design solution and the entire article is dedicated to implement Loosely Couple architecture.

Why loosely couple ?
Let’s think why not loosely couple. If there is tight coupling among the components then change in one will get effect to another. Think about your desktop computer, If RAM does not work, we pull it and plug another one, if HDD does not work we just replace it, It does not require to change mother board when we change RAM or HDD.
Now, let’s think computer hardware is tightly coupled, and then we would buy a complete new system on change of any parts into it, which would be very expensive.
Same goes true for software architecture and this is the reason why everyone wants to achieve it in project development.
OK, fine we have learned the concept of dependency and the concept of coupling in software architecture. Now let’s come in our main discussion.

What is dependency Injection?
Technically speaking, Dependency Injection is architectural solution to achieve loosely coupled architecture.  It is the process of injecting(converting) coupled (dependent) object into decoupled(independent) object is called Dependency Injection. We can implement Dependency Injection in following ways.

1)Constructor Injection
2)property Injection
3)Interface Injection.

The next point should clear, What Dependency Injection can give in terms of architectural benefit.
As we have discussed Dependency Injection is nothing but a way to loosely coupled architecture, so the value of Dependency Injection is hidden within the benefit of loosely coupled architecture. Here is some of them.
·         We should not think about changing of one component (example of desktop computer) in future.
·         Code will be well maintainable and scalable.
·         Requirement change can able to handle in better ways.
·         Helps in Unit Testing, And many more

In this article we will understand only the concept of constructor injection. Before to start with constructor injection we will implement one tight coupled architecture at first and then we will find solution. Here is code implementation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace consoleApp
{
    public class Instrument
    {
        public string InstrumentName { get; set; }
    }
    public class InstrumentPlayer
    {
        public string PlayerName { get; set; }
        public string ReturnInfo(Instrument obj)
        {
            return "Person Name:- "+ PlayerName + " Instrument Naem:- "  + obj.InstrumentName;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Instrument objIns = new Instrument();
            objIns.InstrumentName = "drum";

            InstrumentPlayer objPlayer = new InstrumentPlayer();
            objPlayer.PlayerName = "Sourav Kayal";

            Console.WriteLine(objPlayer.ReturnInfo(objIns));

            Console.ReadLine();
        }
    }
}
The output is here.

The problem with this implementation is , We are instantiating Instrument class within InstrumentPlayer class. And we are sending concrete object of Instrument class as a parameter of ReturnInfo() class. Now if the player wants to play another Instrument tomorrow?
Then we have to define some other instrument class and we have to change the parameter type in  ReturnInfo() function. This is very important part, we have to tune InstrumentPlayer class in additional demand. But if we implement loosely couple architecture, then without touching InstrumentPlayer class we can provide solution. Here is code implementation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace consoleApp
{
    public interface IInstrument
    {
        string InstrumentName();
    }
    public class Drum : IInstrument
    {
        public string InstrumentName()
        {
            return "Drum";
        }
    }

    public class Guiter : IInstrument
    {
        public string InstrumentName()
        {
            return "Guiter";
        }
    }


    public class InstrumentPlayer
    {
        public string PlayerName { get; set; }
        public InstrumentPlayer(String Name, IInstrument obj)
        {
            Console.WriteLine("Person Name:- " + Name + " Instrument Naem:- " + obj.InstrumentName());
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            IInstrument obj1 = new Drum();
            IInstrument obj2 = new Guiter();

            InstrumentPlayer objPlayer = new InstrumentPlayer("Sourav Kayal" , obj1);
            objPlayer = new InstrumentPlayer("Sourav Kayal", obj2);
            Console.ReadLine();
        }
    }
}

Here is sample output.

We have provided solution by introducing the concept of Inheritance in this scenario. Now both class are talking via inherence, Now again if we want to another instrument we will just Implement IInstrument interface to this class and problem will solve.