Tuesday, August 1, 2017

ASP.NET - Web Application Architecture

Web Application works in Client/Server architecture. On Client side you need a web browser that understands HTML and on Server side you need a Web Server to host the application

ASP .NET Web application runs under Microsoft Internet Information Service (IIS).

Let's understand how a request is being handled in web application.

When a user requests for a URL in a web browser, the request goes to the web server (in our case it is IIS) through internet using HTTP protocol (Hyper Text Transfer Protocol). Once the web server, receives the requests it process that request (For example if the data need to be retrieved from database, IIS contacts the application DLL to get the data from database) and send the HTML content back to the browser.

Protocol - Set of standard rules, that describes how two or more items communicate over internet.

ASP .NET - Web Application Introduction

A web application is an application that is accessed by users by using a web browser. Example of web browsers:

  • Microsoft Internet Explorer (IE)
  • Google Chrome
  • Mozilla Firefox
  • Apple Safari
  • Netscape
There are many frameworks to build a web application and ASP.NET is the one among them, that is created by Microsoft to build dynamic data driven web application and web services. ASP .Net is introduced in 2002 and it is the successor of the Classic ASP. 

There are many advantages of having a web application over a desktop application (Example of desktop application is Microsoft Office).

  • Easy Deployment: Desktop application need to be deployed in each of the users's computer who need the access to the application, so lets say if there are 5000 user which requires the same application it has to be installed in 5000 computers. On the other hand a web application is deployed in a web server and accessed using a web URL in a web browser,  and all the 5000 users can access that if they have a wen browser which understand HTML.
  • Ease of Maintenance/Support/Patch: If a bug fix is done in the application, in case of desktop application patch has to be deployed to ease user's system where as in case of web application the patch is only need to be applied to the Web Server where the application is being hosted. 
  • No additional software required to access the web application as long as user has the web browser that can understand HTML, in place of Desktop application each user need to have the application installed in their computers.
  • Cross Platform: In case of desktop application, if the application is developed in Windows platform it can only be accessed in windows OS, to make the application accessible in other platforms it has to be re developed in those platforms, where as in case of web application irrespective of which platform the application is being developed, it can be accessible to the user if user has a browser that understands HTML.
Framework - In simple terms framework is a collection of classes.

Monday, December 12, 2016

"Favor Composition over Inheritance" Is this Correct ???

You must have heard or read "Favour Composition over Inheritance" from may people, many blogs and books.  Here goes my opinion on the same...

Anyone who had worked on .NET framework to build applications has extensvily used both Inheritance as well as Composition. When a class object is being referenced by the another class object, it forms the parent/child hierarchy, where the object being referenced is the object of sub-class and the object which is holding the the referenced object is the super-class object, and this parent-child hierarchy is refereed as Inheritance. When a class uses another object to provide some or all of its functionalities then it's refereed as Composition. 

Whenever Inheritance is being discussed, knowing or unknowingly Composition comes into the picture. Lets understand both the concepts:

  • Both supports code reuse
    • Composition - The purpose of it is to make wholes out of parts using code reuse. 
    • Inheritance - The purpose of it is to make parent-child hierarchy to reuse code (common code defined in parent class). 
  • "Is A" and "Has A" Relationship 
    • Composition is a "Has A" relationship as the the class owns the object of another class.
    • Inheritance is a "Is A" relationship as the sub-class is also a type of super-class hence the object of super class can be used as reference object to hold the object of sub-class.
  • Coupling
    • In case of composition the class object is been used directly by the another class, so the reusable class is robust.
    • In case of Inheritance, the super-class doesn't know anything about the sub-classes so any changes goes into the sub-classes there is no change in the behaviours of super-class but the sub-class knows about the super-class as it inherits all its behaviours so any changes goes into the super-class the sub-classes may get affected which makes a tight coupling between them.
  • Test-ability
    • Composition provided more flexibility for testing as its is easy class to mock objects used inside the class.
    • In case of Inheritance you will need the base class (super-class). Since the derived classes (sub-classes) are tightly coupled with the base class (super-class) it become slightly difficult to mock derived class objects.
    • In case of TDD mocking Composition are far much faster and easier than mocking derived classes.

Many say that go with composition when you need multiple functionalities in a class, as you can't inherit from more than one class in .NET. But what I believe is, if you have only this reason (a class can't inherit from multiple base classes) to go for Composition then you don't have to as we can achieve this by making class implement multiple interfaces.

Both Inheritance & Composition are useful while developing applications. Just that you need to know when to use what? Below are the steps I follow while selecting Inheritance or Composition.
  • First Approach:
    • Use Inheritance when you want to reuse the class without modifying any of its behaviours. Basically If sub-class is adding functionality to the base class go with Inheritance, if sub-class is removing behaviours from the super-class, question inheriting from super-class.
  • Second Approach:
    • Use Inheritance when you have "Is A" relationship like, a car "is a" vehicle. 
    • Use Composition when you have "Has A" relationship like, a car "has an" engine. 

Sunday, December 11, 2016

DIP vs DI vs IoC vs SL

Whenever DIP is discussed, a lot of developers confuse this with DI and IoC. So today we are going to see how these three are different from one another.
  • DIP - Dependency Inversion Principe
    • Its a principle which says 
      • High level modules should not depend on low level modules. Both should dependent upon abstraction.
      • Abstraction should not depend upon details. Details should depend on abstraction.
    • It never say how this principle can be achieved.
  • IoC - Inversion of Control
    • A programming style where a framework or run-time controls the flow.
  • DI - Dependency Injection
    • A software Design Pattern of injecting a class's dependencies into at run-time.
    • DI uses a builder object to initialize objects and provide the required dependencies to the object. 
    • There are three ways to achieve this
      • Constructor Injection
      • Setter Injection (Property Injection)
      • Interface Injection
  • SL - Service Locator
    • Introduces a locator object that, objects use to resolve dependencies.

DIP - Dependency Inversion Principle - Example

In previous post we covered what is DIP. Here I am going to show one more example of DIP.

Lets see a real- time example, we all know that whenever a bill is printed, an invoice is required to be generated and whenever an invoice is generated a bill must be printed. Lets assume that we have two classes Bill and Invoice as below.


When the below code is executed, we get the stack overflow error.

Now how do we solve this issue? This is where DIP comes into the picture, where we inject the dependencies to the dependent object. See the below code how the dependencies are injected to resolve stack overflow issues.



What we saw in above example is to achieve DIP using Constructor injection. 

PS: DIP is just the principle which requires that all your code's entities to depend only on the details they really need. DI is a process of passing the "abstract details" to the entity that really needs these derails. 

Saturday, December 10, 2016

DIP - Dependency Inversion Principle

DIP says - The high-level modules/classes should not depend upon low-level modules/classes. Both should depend upon abstractions. Secondly, abstractions should not depend upon details. Details should depend upon abstractions.

It means that if a class has dependencies on other classes, it should rely on dependencies' interface in place of their concrete types. Basically it helps in developing loosely coupled code.

DIP is some way related to Dependency Injection (DI) pattern but it doesn't imply Dependency Injection. DIP just says that higher layers of your application should not directly depend on lower layers. DIP doesn’t say anything about how higher layers know what lower layer to use. This could be done by using Dependency Injection or Service Locator patterns.

Let's understand DIP with an example: Think of an application which has 4 layers, Presentation Layer, Application Layer, Business Layer and Data Access Layer. The Presentation layer is the highest layer and directly depends on or communicates with the Application Layer. The Application layer is higher level than Business Layer and depends on or communicate with the Business Layer and so on. 

When DIP is applied this relationship between layers are reversed. The Presentation Layer defines the abstractions it needs to interact with the Application Layer.  The Application Layer defines the abstractions it needs to interact with the Business Layer. The Business Layer defines the abstractions it needs to interact with the Data Access Layer. Basically the higher layer defines the abstraction and lower layer implements those abstractions.

Presentation Layer ----> Services Layer -----> Business Components Layer ----> Data Access Layer
DIP may put abstraction in the layers defining them, for example Presentation Layer contains Presentation Layer logic and the Service Layer Abstractions (abstract classes and interfaces). The Services Layer contains Service Logic and Business Layer Abstractions (abstract classes and interfaces) and so on. In this case of DIP application the Data Access Layer depends upon the Business Layer, the Business Layer depends on the Service Layer and the Service Layer depends on the Presentation Layer. The dependencies (references) are inverted hence the name of the principle.


I don't follow the above approach in my projects what I do instead is define Presentation, Services, Business and Data Access Layers as different assemblies. I also make Interfaces as different assemblies like Service Interfaces, Business Interfaces, and Data Access Interfaces.   


Since the layers interacts with each other through interfaces, the second intent (abstractions should not depend  on details. Details should depend on abstractions) of the DIP is also full-filled.  The best part about this principle is, it makes the code unit testable, like in the above example each layer can be tested independently.

Lets see DIP with an example, lets assume that we have a high level class called Manager class which represent a person that manages the workers and a low level class called Worker which represents the person a Manger class manages.

public class Worker {
   public void Work()
   {
        // working...
   }
}

public class Manager {
   private IList<Worker> objWorkers;
   public Manager(List<Worker> workers)
  {
          objWorkers =  workers;
  }
   public void Manage()
  {
        foreach (var worker in objWorkers )
             worker.Work();
   }
}

Let's say now few specialised workers are being introduced. We created a new class SuperWorker for this.

public class SuperWorker {
   public void Work()
   {
        // working...
   }
}

Now will have to be modified Manager class to accommodate SuperWorker class, which is going to break OCP. So how should we resolve this issues? This is where the DIP comes into the picture. Now create and IWorker interface and make Manager use IWorker instead of Work class. 

public interface IWorker{
    public void Works();
}

public class Worker : IWorker {
   public void Work()
   {
        // working...
   }
}

public class SuperWorker : IWorker {
   public void Work()
   {
        // working...
   }
}

public class Manager {
   private IList<IWorkable > objWorkers;
   public Manager(List<IWorkable > workers)
  {
          objWorkers =  workers;
  }

   public void Manage()
  {
        foreach (var worker in objWorkers )
             worker.Work();
   }
}

Let's say now a Robot is being introduce the only thing we need to do is make Robot implement the IWorker interface & no additional changes in the existing classes.

public class Robot: IWorker {
   public void Work()
   {
        // working...
   }
}

ISP - Interface Segregation Principle

ISP says - Many client-specific interfaces are better than one general-purpose interface. 
(The clients should not be forced to implement interfaces they don't use. Instead of one fat interface many small interfaces are preferred based on groups of methods, each one serving one sub module.)

This means that create the interfaces such a way that it is closely related to the code that uses it than the code which is going to implement it (Basically it says that define interfaces based on the methods which clients need than which method class implements). So that clients are not forced to implement the interfaces which they do not use.

Basically ISP is nothing but Interface Re-engineering.  

Let's see ISP with an example, suppose we have an application to print Documents and PDFs, we can print the Documents and PDFs either in colour or no-colour.

interface IPrint{
     public void Print();
     public void SetColour();
}

class Document : IPrint{
  // interface or other implementation goes here
}

class PDF: IPrint {
  // interface or other implementation goes here
}

Lets say now a new requirement comes to add the TextDocument. As we already have IPrint interface we can ask TextDocument to implement the interface IPrint but then the TextDocument class doesn't need SetColour() method because text are never required to be printed in colour. How do we over come this issue? This is where the ISP comes into the picture.

First lets try to divide IPrint interface to two interface as below:
interface IPrint{
   public void Print();
}

interface IColour {
   public SetColour();
}

Then ask new class TextDocument to implement IPrint() and existing classes to implement IColour as well as IPrint. Well, this would be wrong as it violates OCP in existing Document and PDF classes (since we are modifying them to implement the new interface). We shouldn't be modifying the exiting classes, so how should we resolve this issues now?

Well, this can be done easily, by introducing a new interface IBasePrint and moving Print() method in it and making interface IPrint and class TextDocument to implements interface IBasePrint.

interface IBasePrint{
    public Print();
}

inteface IPrint : IBasePrint
{
     public SetColour();
}

class TextDocument: IBasePrint
{
  // interface or other implementation goes here
}

PS: Like Classes, each interface should have a specific purpose/responsibility (refer to SRP). Don't force the class to implement an interface when object doesn't share the purpose. The larger the interface, the more likely it includes methods that are not required by all implementer.