Search This Blog

Friday 11 December 2015

Dependency Injection

People are often confused about what Dependency Injection is and when they might need or want to use it. Some time ago I wrote an article Managing Dependency Injection in C# with Autofac which explains how to manage DI in C#, but today I want to show by simple code sample what actually Dependency Injection is.
Imaging situation where you have a class, let's say Employee, and two or more different loggers for that class. Each logger prints messages in his own particular way and you want to have control of which logger to use for Employee during its instantiation.
Just take a look at this code and I'm sure you will get the idea of Dependency Injection:

public class Employee
{
    public Employee(ILogger logger)
    {
        logger.WriteToLog("New employee created");
    }
}
public interface ILogger
{
    void WriteToLog(string text);
}
public class LoggerOne : ILogger
{
    public void WriteToLog(string text)
    {
        Console.WriteLine(text);
    }
}
public class LoggerTwo : ILogger
{
    public void WriteToLog(string text)
    {
        Console.WriteLine("***********\n {0}\n***********", text);
    }
}
Now let's instantiate an Employee with two different loggers:

Employee employee1 = new Employee(new LoggerOne());
Employee employee2 = new Employee(new LoggerTwo());
And the output:
New employee created
*******************
New employee created
*******************

The advantages of using Dependency Injection pattern and Inversion of Control are the following:

•Reduces class coupling

•Increases code reusing

•Improves code maintainability

•Improves application testing

Thursday 10 December 2015

When interface and when abstract class

If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
    If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.


Example(a very rudimentary one!):Consider a base class called Customer which has abstract methods like CalculatePayment(), CalculateRewardPoints() and some non-abstract methods like GetName(), SavePaymentDetails().

Specialized classes like RegularCustomer and GoldCustomer will inherit from the Customer base class and implement their own CalculatePayment() and CalculateRewardPoints() method logic, but re-use the GetName() and SavePaymentDetails() methods.

You can add more functionality to an abstract class(non abstract methods that is) without affecting child classes which were using an older version. Whereas adding methods to an interface would affect all classes implementing it as they would now need to implement the newly added interface members.

http://javarevisited.blogspot.in/2013/05/difference-between-abstract-class-vs-interface-java-when-prefer-over-design-oops.html

Method Overloading in c#.net

Method Overloading means to have two or more methods with same name in the same class with different arguments. The benefit of method overloading is that it allows you to implement methods that support the same semantic operation but differ by argument number or type.

Important Points

    Overloaded methods MUST change the argument list
    Overloaded methods CAN change the return type
    Overloaded methods CAN change the access modifier
    Overloaded methods CAN declare new or broader checked exceptions
    A method can be overloaded in the same class or in a subclass


You can not overload the function by differ only their return type . You can only overload the function in following ways

    Parameter types
    Number of parameters
    Order of the parameters declared in the method

You can not come to know which function is actually called (if it was possible).

One more thing I would like to add is function overloading is providing a function with the same name, but with a different signature. but the return type of a method is not considered as a part of method's signature.

using System;

namespace ProgramCall
{

    class Class1
    {

        public int Sum(int A, int B)
        {
            return A + B;
        }

        public float Sum(int A, float B)
        {
            return A + B;
        }
    }

    class Class2 : Class1
    {
        public int Sum(int A, int B, int C)
        {
            return A + B + C;

        }
    }

    class MainClass
    {
        static void Main()
        {

            Class2 obj = new Class2();

            Console.WriteLine(obj.Sum(10, 20));

            Console.WriteLine(obj.Sum(10, 15.70f));

            Console.WriteLine(obj.Sum(10, 20, 30));

            Console.Read();
        }

    }
}

Facade Pattern

Facade Pattern:
Facade pattern falls under Structural Pattern of Gang of Four (GOF) Design Patterns in .Net. The Facade design pattern is particularly used when a system is very complex or difficult to understand because system has a large number of interdependent classes or its source code is unavailable. In this article, I would like share what is facade pattern and how is it work?

What is facade Pattern:
Facade pattern hides the complexities of the system and provides an interface to the client using which the client can access the system.
This pattern involves a single wrapper class which contains a set of members which are required by client. These members access the system on behalf of the facade client and hide the implementation details.
The facade design pattern is particularly used when a system is very complex or difficult to understand because system has a large number of interdependent classes or its source code is unavailable.


In Factory pattern, we create object without exposing the creation logic. In this pattern, an interface is used for creating an object, but let subclass decide which class to instantiate. The creation of object is done when it is required. The Factory method allows a class later instantiation to subclasses.

Abstract factory pattern

Design patterns:

Design patterns are general reusable solutions to common problems that occurred in software designing. There are broadly 3 categories of design patterns, i.e., Creational, Behavioral and Structural.

Abstract factory pattern in very useful in GUI based applications where we need to create related GUI components. My example here is solely for the purpose of understanding and there is no way the "Cell-phone-information-system" be designed this way (otherwise we will end up adding new classes every week). Please do let me know if I missed something. Perhaps for the experienced guys this article is not very useful but it could really be useful for beginners.

It is used to create a set of related objects, or dependent objects. Internally, Abstract Factory use Factory design pattern for creating objects. It may also use Builder design pattern and prototype design pattern for creating objects. It completely depends upon your implementation for creating objects. 


What is Abstract Factory Pattern?
Abstract Factory patterns acts a super-factory which creates other factories. This pattern is also called as Factory of factories. In Abstract Factory pattern an interface is responsible for creating a set of related objects, or dependent objects without specifying their concrete classes.


When to use it?

    Create a set of related objects, or dependent objects which must be used together.
    System should be configured to work with multiple families of products.
    The creation of objects should be independent from the utilizing system.
    Concrete classes should be decoupled from clients.

Note:

    Internally, Abstract Factory use Factory design pattern for creating objects. But it can also use Builder design pattern and prototype design pattern for creating objects. It completely depends upon your implementation for creating objects.
    Abstract Factory can be used as an alternative to Facade to hide platform-specific classes.
    When Abstract Factory, Builder, and Prototype define a factory for creating the objects, we should consider the following points :
        Abstract Factory use the factory for creating objects of several classes.
        Builder use the factory for creating a complex object by using simple objects and a step by step approach.
        Prototype use the factory for building a object by copying an existing object.

Factory Method pattern

In Factory Method pattern, we create object without exposing the creation logic. In this pattern, an interface is used for creating an object, but let subclass decide which class to instantiate. The creation of object is done when it is required. The Factory method allows a class later instantiation to subclasses.



C# - Implementation Code

    interface Product
    {
    
    }
    
    class ConcreteProductA : Product
    {
    }
    
    class ConcreteProductB : Product
    {
    }
    
    abstract class Creator
    {
     public abstract Product FactoryMethod(string type);
    }
    
    class ConcreteCreator : Creator
    {
     public override Product FactoryMethod(string type)
     {
     switch (type)
     {
     case "A": return new ConcreteProductA();
     case "B": return new ConcreteProductB();
     default: throw new ArgumentException("Invalid type", "type");
     }
     }
    }

***************************************************************************************************************
Another C# - Implementation for FactoryMethod design pattern:

interface IIceCream


{


    string Functionality();


}


class ChocolateIceCream : IIceCream


{


    public string Functionality()


    {


        return "Chocolate Ice cream";


    }


}


class VanillaIceCream : IIceCream


{


    public string Functionality()


    {


        return "Vanilla Ice cream";


    }


}


class StrawberryIceCream : IIceCream { public string Functionality()


    {


        return "Strawberry Ice cream";


    }


}

This is the basic structure
of our program. Now we need to implement the "Factory Method", which
will create the instance of our desired ice-cream at run-time. So we
will create this method now.

This is how I’m going to do this.



static class Factory


{


   /// <summary>    /// This is the Factory method   

/// </summary>   

public static IIceCream Get(int id)


   {


       switch (id)


       {


           case 0:


                return new ChocolateIceCream();


           case 1:


                return new VanillaIceCream();


           case 2:


                return new StrawberryIceCream(); default:


                return null;


        }
   }
}



The Repository Pattern

The Repository Pattern

Context

In many applications, the business logic accesses data from data stores such as databases, SharePoint lists, or Web services. Directly accessing the data can result in the following:
  • Duplicated code
  • A higher potential for programming errors
  • Weak typing of the business data
  • Difficulty in centralizing data-related policies such as caching
  • An inability to easily test the business logic in isolation from external dependencies

Objectives

Use the Repository pattern to achieve one or more of the following objectives:
  • You want to maximize the amount of code that can be tested with automation and to isolate the data layer to support unit testing.
  • You access the data source from many locations and want to apply centrally managed, consistent access rules and logic.
  • You want to implement and centralize a caching strategy for the data source.
  • You want to improve the code's maintainability and readability by separating business logic from data or service access logic.
  • You want to use business entities that are strongly typed so that you can identify problems at compile time instead of at run time.
  • You want to associate a behavior with the related data. For example, you want to calculate fields or enforce complex relationships or business rules between the data elements within an entity.
  • You want to apply a domain model to simplify complex business logic.

Solution

Use a repository to separate the logic that retrieves the data and maps it to the entity model from the business logic that acts on the model. The business logic should be agnostic to the type of data that comprises the data source layer. For example, the data source layer can be a database, a SharePoint list, or a Web service.
The repository mediates between the data source layer and the business layers of the application. It queries the data source for the data, maps the data from the data source to a business entity, and persists changes in the business entity to the data source. A repository separates the business logic from the interactions with the underlying data source or Web service. The separation between the data and business tiers has three benefits:
  • It centralizes the data logic or Web service access logic.
  • It provides a substitution point for the unit tests.
  • It provides a flexible architecture that can be adapted as the overall design of the application evolves.