Monday, February 27, 2012

OOPS : An introduction to the SOLID principles of OO design

Single Responsibility Principle

"There should never be more than one reason for a class to change." — Robert Martin, SRP paper linked from The Principles of OOD
My translation: A class should concentrate on doing one thing
The SRP says a class should focus on doing one thing, or have one responsibility. This doesn’t mean it should only have one method, but instead all the methods should relate to a single purpose (i.e. should be cohesive).
For example, an Invoice class might have the responsibility of calculating various amounts based on it’s data. In that case it probably shouldn’t know about how to retrieve this data from a database, or how to format an invoice for print or display.
A class that adheres to the SRP should be easier to change than those with multiple responsibilities. If we have calculation logic and database logic and display logic all mixed up within one class it can be difficult to change one part without breaking others. Mixing responsibilities also makes the class harder to understand, harder to test, and increases the risk of duplicating logic in other parts of the design (decreases cohesion, functionality has no clear place to live).
Violations of the SRP are pretty easy to notice: the class seems to be doing too much, is too big and too complicated. The easiest way to fix this is to split the class.
The main trick in following the SRP is deciding how to define the single responsibility. There may be many ways to dissect a feature into responsibilities, but the ideal way is to use responsibilities that are likely to change independently, hence the official description: "A class should have one, and only one, reason to change".

Open Closed Principle

"Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification." — Robert Martin paraphrasing Bertrand Meyer, OCP paper linked from The Principles of OOD
My translation: Change a class’ behaviour using inheritance and composition
Bob Martin’s initial paper on the OCP linked from The Principles of OOD attributes the idea to Bertrand Meyer, who wrote that classes should be “open for extension, but closed for modification”[2]. The idea is that we can use OO techniques like inheritance and composition to change (or extend) the behaviour of a class, without modifying the class itself.
Say we have an OrderValidation class with one big Validate(Order order) method that contains all rules required to validate an order. If the rules change, we need to change or OrderValidation class, so we are violating the OCP. If the OrderValidation contained a collection of IValidationRule objects that contained the rules, then we could write Validate(Order order) to iterate through those to validate the order. Now if the rules change then we can just create a new IValidationRule and add it to an OrderValidation instance at run time (rather than to the class definition itself).
Following the OCP should make behaviour easier to change, and also help us avoid breaking existing behaviour while making changes. The OCP also gets us to think about the likely areas of change in a class, which helps us choose the right abstractions required for our design.
If you find you need to modify a similar area of code all the time (for example, validation rules) then it’s probably time to apply the OCP and abstract away the changing part of the code. Another sign of a potential OCP violation is switching on a type — if another type is created then we’ll have to alter the switch statement. A healthy dose of polymorphism is generally the best treatment. :) I generally think of the OCP as an advertisement for the Template Method and Strategy design patterns.

Liskov Substitution Principle

"Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it." — Robert Martin, LSP paper linked from The Principles of OOD
My translation: Subclasses should behave nicely when used in place of their base class
The LSP sounds deceptively straightforward — we should be able to substitute an instance of a subclass for its parent class and everything should continue to work. Easy right? Well, actually, no it’s not, which is probably why we are often advised to favour composition over inheritance. Ensuring a base class works in any situation the parent does is really hard work, and whenever you use inheritance its a good idea to keep the LSP firmly in mind.
The canonical example of an LSP violation (in fact, the one used in the Hanselminutes episode on SOLID mentioned earlier) is the Square IS-A Rectangle relationship. Mathematically a square is a special case of a rectangle with all sides of equal length, but this breaks the LSP when modelled in code. What should SetWidth(int width) do when called on a Square? Should it set the height as well? What if you have a reference to it via its base class, Rectangle? If you have code that expects one behaviour but gets another depending on which subtype it has, you can wind up with some very hard to find bugs.
LSP violations can be easy to miss until you actually hit the condition where your inheritance hierarchy breaks down (I mean, a square IS-A rectangle, right?). The best way to reduce violations is to keep very aware of the LSP whenever using inheritance, including considering avoiding the problem using composition where appropriate.

Interface Segregation Principle

"Clients should not be forced to depend upon interfaces that they do not use." — Robert Martin, ISP paper linked from The Principles of OOD
My translation: Keep interfaces small and cohesive
The ISP is about keeping interfaces (both interface, and abstract class types of interfaces*) small and limited only to a very specific need (a single responsibility even :)). If you have a fat interface then you are imposing a huge implementation burden on anyone that wants to adhere to that contract. Worse still is that there is a tendency for class to only provide valid implementations for a small portion of a fat interface, which greatly diminishes the advantages of having an interface at all (note that these partial implementations violate the LSP, as we can no longer treat all subclasses of the interface equally).
* While I originally wrote this in terms of interface code constructs, I’ve always thought more about the interface in ISP as the public interface for interacting with an object, even if this is just the public methods of a class. This becomes more relevant in dynamic languages where interfaces are implied rather than explicit. In the dynamic languages case, ISP becomes more a statement of SRP: keeping a small interface to expose a single responsibility. [Added 2011-02-18]
The first time I recognised a violation of the ISP was writing a minimal implementation of an ASP.NET RoleProvider, which required an implementation of the following methods:
public class MyRoleProvider : RoleProvider {
    public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config) { ... }
 public override void AddUsersToRoles(string[] usernames, string[] roleNames) { ... }
 public override string ApplicationName { get { ... } set { ... } }
 public override void CreateRole(string roleName) { ... }
 public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { ... }
 public override string[] FindUsersInRole(string roleName, string usernameToMatch) { ... }
 public override string[] GetAllRoles() { ... }
 public override string[] GetRolesForUser(string username) { ... }
 public override string[] GetUsersInRole(string roleName) { ... }
 public override bool IsUserInRole(string username, string roleName) { ... }
 public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { ... }
 public override bool RoleExists(string roleName) { ... }
}
In my case I just wanted to use ASP.NET’s built in facility for securing pages by role in the web.config, which means I needed to implement GetRolesForUser(...) and Initialize(...). Can you guess what the other implementations were? That’s right, throw new NotImplementedException();. This is very bad — if we have a RoleProvider instance we have no idea what sub-features it will support. On top of that we also have a lot of useless noise in our class. (If you like the RoleProvider, you might also enjoy the MembershipProvider.)
The way to fix violations like this is to break down interfaces along the lines of responsibilities and apply the SRP. For the RoleProvider case, even if we just split it into IRolesForUserLookup and IRoleManagement (yuk), that would let us only implement what we need. If we need all the features then we can implement both interfaces, but we should not be forcing clients to fake or throw in implementations that are meaningless to them.

Dependency Inversion Principle

"A. High level modules should not depend upon low level modules. Both should depend upon abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions." — Robert Martin, DIP paper linked from The Principles of OOD

My translation: Use lots of interfaces and abstractions
The DIP says that if a class has dependencies on other classes, it should rely on the dependencies’ interfaces rather than their concrete types. The idea is that we isolate our class behind a boundary formed by the abstractions it depends upon. If all the details behind those abstractions change then our class is still safe. This helps keep coupling low and makes our design easier to change.
At its simplest, this can just be the difference between referencing an EmployeeFinder class or an IEmployeeFinder interface. The concrete EmployeeFinder class can access a database or a file, but the client class only cares that it meets the IEmployeeFinder contract. Better yet, our client class doesn’t have to be tied in any way to the EmployeeFinder class. It could instead use SqlEmployeeFinder, XmlEmployeeFinder, WebServiceEmployeeFinder or MockEmployeeFinder.
Where the DIP starts to become really useful and a bit more profound is in a related concept, Dependency Injection. Dependency Injection is about getting other code to insert the actual dependency instances into our class, so we don’t even have the client class newing up any of the concrete instances. This completely isolates our class and makes change and reuse much easier. (I’ve covered some introductory stuff in a previous ramble on dependency injection).
The other side of the DIP relates to dependencies between high and low level modules in layered applications. For example, a class accessing the database should not depend on a UI form used to display that data. Instead the UI should rely on an abstraction (or abstractions) over the database access class. Traditional application layers (data, logic, ui) seem largely replaced by MVC, onions and hexagons these days, so I tend to think about the DIP entirely from the point of view of abstracting dependencies.

SOLID principles as a whole

You can probably see that the SOLID principles overlap a lot. For example, the SRP provides a good way of splitting interfaces to follow the ISP. The ISP helps implementers conform to the LSP by making implementations small and cohesive. You may also notice that some of the principles contradict, or at least pull in opposing directions, such as the OCP requiring inheritance while the LSP tends to discourage it[3]. This interplay between the principles can provide a really useful guide while developing your design. I’m believe there are no perfect designs, just trade offs, and the SOLID principles can help you evaluate these and achieve a good balance. The fact that there is some measure of conflict between them also makes it obvious that none of the principles should be applied rigidly or dogmatically. Do you really need a huge interface explosion due while adhering to the OCP and DIP? Maybe, maybe not. But considering your design options in light of the SOLID principles can help you decide.
A lot of SOLID principles seem to fall out fairly naturally if you practice TDD (or BDD). For example, writing an effective unit test for a class is much easier if you follow the DIP and isolate your class from its dependencies. If you are writing the tests first to drive your design, then your class will naturally tend to use the DIP. If you are retro-fitting tests, then you’ll likely encounter more difficulties testing, and may end up with interaction-style tests, re-writing the class to use the DIP, or worse, throwing it in the too hard-to-test basket.
This is what people mean when they say that TDD and "testability" is not about testing, it is about design. Scott Bellware recently published a good post on design, SOLID and testability that goes into this in more detail.

Thursday, February 16, 2012

Design Pattern : Chain of Responsibility pattern Implementation

Definition

GoF -> A way of passing a request between a chain of objects
  1. The Chain of Responsibility pattern works with a list of Handler objects that have limitations on the nature of the requests they can deal with. If a handler object cannot handle a request, it passes it on to the next handler object in the chain. At the end of the chain, there can be either default or exceptional behavior.
  2. The pattern chains the receiving objects together, and then passes any request messages from object to object until it reaches an object capable of handling the message.
  3. Chain of Responsibility simplifies object interconnections. Instead of senders and receivers maintaining references to all candidate receivers, each sender keeps a single reference to the head of the chain, and each receiver keeps a single reference to its immediate successor in the chain.
  4. Sometimes, the request object has to go through the chain objects mandatorily, like Http pipeline.
  5. Sometimes only through few handlers.
Design

Let us take an example; we are conducting a GK context. We have three teams to answer the questions. Each team will have 10000 ms to answer the questions, and team one has to start the each question. If team one didn't answer the question, it will be passed on to the next team.

Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

UML Diagram

From GoF

chain1.gif

chain2.gif

Code

---------------- handler Base class ----------------------
public abstract class Handlerbase
    {
        public Handlerbase NextTeam { get; private set; }
        public ContextObject Question { get; private set; }
        public Handlerbase(Handlerbase nextHandler, ContextObject question)
        {
            NextTeam = nextHandler;
            Question = question;
        }

        public abstract void HandleRequest();
    }
    ---------------- queue object one ----------------------
public class TeamOne: Handlerbase
    {
        public TeamOne(Handlerbase nextHandler, ContextObject question) : base(nextHandler, question) { }
        public override void HandleRequest()
        {
            Console.WriteLine("Question : {0}", Question.Question.ToString());
            Console.WriteLine("*******************************************"));
            Console.WriteLine("Wating for team one to respond");
            Thread.Sleep(10000);
            Console.WriteLine("\t no response from team one.....");
            NextTeam.HandleRequest();
        }
    }
    ---------------- chain object two ----------------------
    public class TeamTwo : Handlerbase
    {
        public TeamTwo(Handlerbase nextHandler, ContextObject question) : base(nextHandler, question) { }
        public override void HandleRequest()
        {
            Console.WriteLine("Wating for team two to respond");
            Thread.Sleep(10000);
            Console.WriteLine("\t no response from team two.....");
            NextTeam.HandleRequest();
        }
    }
    ---------------- chain object tree ----------------------
    public class TeamThree : Handlerbase
    {
        public TeamThree(Handlerbase nextHandler, ContextObject question) : base(nextHandler, question) { }
        public override void HandleRequest()
        {
            Console.WriteLine("Wating for team three to respond");
            Thread.Sleep(10000);
            Console.WriteLine("\t no response from team three as well .....");
        }
    }
    ---------------- Request----------------------
    public class ContextObject
    {
        public string Question { get; set; }
    }
   ---------------- Client----------------------
        static void Main(string[] args)
        {
            ContextObject question = new ContextObject() { Question = "Who is an ediat in your team?" };
            TeamThree teamThree = new TeamThree(null, question);
            TeamTwo teamTwo = new TeamTwo(teamThree, question);
            TeamOne teamOne = new TeamOne(teamTwo, question);
            teamOne.HandleRequest();
            Console.ReadKey();
        }
  
Another Example:

To consider a more formal example, assume a scenario where you’ve a banking system, and you want to implement some kind of Loan approval. The customer may request a loan, and if it is below a specific amount, the cashier may  approve it directly. If it is above the specified amount, he might pass the request to his manager for approval.
So you may use Chain Of Responsibility implementation to hand over the request/command to the correct approver. For an example, consider this implementation of the above Bank account scenario. Our business rule is something like, a cashier can approve the request if the amount is lesser than 1000 $$, other wise the approval should be passed to the manager. The manager can approve the request if the amount is lesser than 10,000 $$.
We have the following components.
  • LoanRequest – A concrete request
  • IRequestHandler – Abstract request handler implementation
    • Concrete handlers like Cashier and Manager implements this
    • Has a reference to the successor to pass the request
  • Program – The main driver

To the code 

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

namespace DesignPatternsCof
{


    //Request
    class LoanRequest
    {
        public string Customer { get; set; }
        public decimal Amount { get; set; }
    }

    //Abstract Request Handler
    interface IRequestHandler
    {
        string Name { get; set; }
        void HandleRequest(LoanRequest req);
        IRequestHandler Successor { get; set; }
    }

    //Just an extension method for the passing the request
    static class RequestHandlerExtension
    {
        public static void TrySuccessor(this IRequestHandler current, LoanRequest req)
        {

            if (current.Successor != null)
            {
                Console.WriteLine("{0} Can't approve - Passing request to {1}", current.Name, current.Successor.Name);
                current.Successor.HandleRequest(req);
            }
            else
            {
                Console.WriteLine("Amount invaid, no approval given");               
            }
        }
    }

    //Concrete Request Handler - Cachier
    //Cachier can approve requests upto 1000$$
    class Cashier : IRequestHandler
    {
        public string Name { get; set; }
       
        public void HandleRequest(LoanRequest req)
        {
            Console.WriteLine("\n----\n{0} $$ Loan Requested by {1}",
                  req.Amount, req.Customer);

           if (req.Amount<1000)
               Console.WriteLine("{0} $$ Loan approved for {1} - Approved by {2}",
                    req.Amount,req.Customer, this.Name);
           else
               this.TrySuccessor(req);
        }

        public IRequestHandler Successor { get; set; }      
    }

    //Concrete Request Handler - Manager
    //Manager can approve requests upto 10000$
    class Manager : IRequestHandler
    {
        public string Name { get; set; }
        public void HandleRequest(LoanRequest req)
        {
            if (req.Amount < 10000)
                Console.WriteLine("{0} $$ Loan approved for {1} - Approved by {2}",
                         req.Amount, req.Customer, this.Name);
            else
               this.TrySuccessor(req);

        }
        public IRequestHandler Successor { get; set; } 
    }

  

    //Main driver
    class Program
    {
        static void Main(string[] args)
        {
            //Customers
            var request1 = new LoanRequest() { Amount = 800, Customer = "Jimmy"};
            var request2 = new LoanRequest() { Amount = 5000, Customer = "Ben"};
            var request3 = new LoanRequest() {Amount = 200000, Customer = "Harry"};

            //Approvers, chained together
            var manager = new Manager() {Name = "Tom, Manager"};
            var cashier = new Cashier(){ Name = "Job, Cachier", Successor = manager};

            //All customers request cashier first to approve
            cashier.HandleRequest(request1);
            cashier.HandleRequest(request2);
            cashier.HandleRequest(request3);

            Console.ReadLine();
        }


    }
And this is what you’ll see upon execution.
image
So, you may observe that Loan Requests from different customers are passed to the cashier in the above example, and the cashier in his approve method passes the request to his successor (i.e, the manager) if the amount is higher than what he can approve. The implementation is pretty minimal, as you can see.
image
We actually  have an Abstract request handler implementation IReqeustHandler and two concrete request handlers, Cashier and Manager. Each request handler may hold a reference to the successor. You may see that we are setting the Successor of Cashier as Manager, so if the  amount requested his beyond a limit, the cashier may pass it to the manager for his approval.

Reference:

Design Pattern : Template pattern Implementation

Template pattern is a behavioral pattern. Template pattern defines a main process template and this main process template has sub processes and the sequence in which the sub processes can be called. Later the sub processes of the main process can be altered to generate a different behavior.

Punch :- Template pattern is  used in scenarios where we want to create  extendable behaviors in generalization and specialization relationship.

For example below is a simple process to format data and load the same in to oracle. The data can come from various sources like files, SQL server etc. Irrespective from where the data comes, the overall general process is to load the data from the source, parse the data and then dump the same in to oracle.


Figure: - General Process

Now we can alter the general process to create a CSV file load process or SQL server load process by overriding ‘Load’ and ‘Parse’ sub process implementation.


Figure: - Template thought Process

You can see from the above figure how we have altered ‘Load’ and ‘Parse’ sub process to generate CSV file and SQL Server load process. The ‘Dump’ function and the sequence of how the sub processes are called are not altered in the child processes.

In order to implement template pattern we need to follow 4 important steps:-

  1. Create the template or the main process by creating a parent abstract class.
  2. Create the sub processes by defining abstract methods and functions.
  3. Create one method which defines the sequence of how the sub process methods will be called. This method should be defined as a normal method so that we child methods cannot override the same.
  4. Finally create the child classes who can go and alter the abstract methods or sub process to define new implementation.

public abstract class GeneralParser
    {
        protected abstract void Load();

        protected abstract void Parse();
        protected virtual void Dump()
        {
            Console.WriteLine("Dump data in to oracle");
        }
        public void Process()
        {
            Load();
            Parse();
            Dump();
        }
    }

The ‘SqlServerParser’ inherits from ‘GeneralParser’ and overrides the ‘Load’ and ‘Parse’ with SQL server implementation.

public class SqlServerParser : GeneralParser
    {
        protected override void Load()
        {
            Console.WriteLine("Connect to SQL Server");
        }
        protected override void Parse()
        {
            Console.WriteLine("Loop through the dataset");
        }     
       
    }

The ‘FileParser’ inherits from General parser and overrides the ‘Load’ and ‘Parse’ methods with file specific implementation.

public class FileParser : GeneralParser
    {
        protected override void Load()
        {
            Console.WriteLine("Load the data from the file");
        }
        protected override void Parse()
        {
            Console.WriteLine("Parse the file data");
        }
     
    }

From the client you can now call both the parsers.

FileParser ObjFileParser = new FileParser();
ObjFileParser.Process();
Console.WriteLine("-----------------------");
SqlServerParser ObjSqlParser = new SqlServerParser();
ObjSqlParser.Process();
Console.Read();

The outputs of both the parsers are shown below.

Load the data from the file
Parse the file data
Dump data in to oracle
-----------------------
Connect to SQL Server
Loop through the dataset
Dump data in to oracle
 
Note: any generic Class is by default implementing This Pattern. i.e. Generic Repository 

Reference:
http://www.codeproject.com/Articles/28402/Design-pattern-FAQ-part-4

Lazy Loading in C# 4.0


Introduction

The “Lazy Loading” design pattern actually equips the developer with the art of providing data only when a property is called for. In other words, it is a on-demand loading. It is an efficient technique to improve performance.

Using the code

For the explanation, I have taken a simple scenario. Say we have classes PersonalLoan and Loan, as shown below.
public class PersonalLoan 
{ 
    public string AccountNumber { get; set; }
    public string AccounHolderName { get; set; }
    public Loan LoanDetail { get; set; }       
    public PersonalLoan(string accountNumber)
    {
        this.AccountNumber = accountNumber;
        this.AccounHolderName = getAccounHolderName(accountNumber);
    } 
}
public class Loan
{
    public string AccountNumber { get; set; }
    public float LoanAmount { get; set; }
    public bool IsLoanApproved { get; set; }
    public Loan(string accountNumber)
    { 
        Console.WriteLine("loan class constructor called.....");
        this.AccountNumber = accountNumber;
        this.LoanAmount = 1000;
        this.IsLoanApproved = true;
        Console.WriteLine("loan object created.....");
    }
}
For explanation's sake, we will assume that AccountNumber and AccounHolderName are not so costly operations in terms of memory occupation and time consumption. On the other hand, LoanDetail is a costly operation and is not used so often. So while designing a class, we may expect that it is better not to have the detail and to populate it when the object property “LoadDetail” is accessed. Please note that the PersonalLoan constructor does not load the LoanDetail property right this point.
In order to archive LazyLoading, we need to change our code a little and it should look like:
public class PersonalLoan
{ 
    private Loan _loanDetail;
    public string AccountNumber { get; set; }
    public string AccounHolderName { get; set; }
    public Loan LoanDetail 
    { 
        get { return _loanDetail ?? (_loanDetail = new Loan(this.AccounNumber)); }
    }
    public PersonalLoan(string accountNumber)
    {
        this.AccounNumber = accountNumber;
        this.AccounHolderName = getAccounHolderName(accountNumber);
    }
} 
In this way, we make sure that “LoanDetail” will be populate only when the property is called rather than when the object for “PersonalLoan” is instantiated. For details, please check PersonalLoan.cs in the attached project.
Now taking this a step ahead, let's look what .NET 4.0 has in this respect. 4.0 introduces a “Lazy<T>” class to support lazy initialization, where “T” specifies the type of object that is being lazily initialized. This is a new feature of C# 4.0 and it can be used when we are working with large objects. The implementation is quite similar to what we have done in the last example.
public class PersonalLoanLazyClass
{
    private readonly Lazy<Loan> lazyLoan;
    public string AccountNumber { get; set; }
    public string AccounHolderName { get; set; }
    public Loan LoanDetail
    {
        get { return this.lazyLoan.Value; }
    }        
    public PersonalLoanLazyClass(string accountNumber)
    {
        Console.WriteLine("PersonalLoanLazyClass Object Initializ: call to costructor....");
        this.AccountNumber = accountNumber;
        this.AccounHolderName = getAccounHolderName(accountNumber);
        this.lazyLoan = new Lazy<Loan>(() => new Loan(this.AccountNumber));
        Console.WriteLine("Completed initialization.......");
    }
}
For details, please check PersonalLoanLazyClass.cs in the attached project. You can check out lazy loading by adding the following lines of code to the executing program:
static void Main(string[] args)
{
    var personalLoan = new PersonalLoanLazyClass("123456789");
    Console.WriteLine("\n\n.......................Press Enter " + 
            "to continue.......................\n\n");
    Console.Read();
    Console.WriteLine(personalLoan.LoanDetail.LoanAmount.ToString());
    Console.Read();
    Console.Read();
}
Output:
output.png


Another Example:
Lazy loading is a pattern which delay initialization of object. C# 4.0 introduced new class which defers the creation of expensive objects when not in use. In this article I’ll explain the use of Lazy<T> class. Suppose we have Customer class and one customer can have many Accounts, if you want show Accounts for one customer, you need to load accounts associated with customer. Loading of accounts can make performance hit badly if data is huge while initializing Customer object. To avoid this situation Lazy loading comes for rescue. Loading of Accounts will only happen when you will use accounts list. This will make sure fast loading of customer object and give performance boost to application.

Here I am explaining example of Customer and Accounts relationship by Lazy loading:
First we create entity classes of Customer and Account:
01.public class Account
02.{
03.public int Id { get; set; }
04. 
05.}
06.public class Customer
07.{
08.public string Name { get; set; }
09.public int CustomerId { get; set; }
10. 
11.public List GetAccounts()
12.{
13.return lazylist.Value;
14.}
15. 
16.Lazy<List<Account>> lazylist;
17. 
18.public Customer(string name, int id)
19.{
20.Console.WriteLine("Initializing Customer Object");
21.Name = name;
22.CustomerId = id;
23.lazylist = new Lazy<List<Account>>(() => { return GetAccountList(id); });
24.Console.WriteLine("Initialization done");
25.}
26. 
27.private List GetAccountList(int id)
28.{
29.Console.WriteLine("Loading Accounts:");
30.List list = new List();
31.Parallel.For(100, 110, (int i) =>
32.{
33.Account a = new Account();
34.a.Id = i;
35.list.Add(a);
36.});
37.return list;
38.}
39.}
In the constructor of customer class, properties are initializing and declaring lazylist object, which is generic List of account and filled by GetAccountList method. This method will only call when lazylist object will be use. Below is main method which shows behavior of lazy loading:
01.static void Main(string[] args)
02.{
03. 
04.Customer cust = new Customer("Neeraj", 1);//constructor should not load accounts
05. 
06.foreach(Account ac in cust.GetAccounts())// it will actually load accounts, ie. lazy loading
07.Console.WriteLine("Id:{0}",ac.Id);
08. 
09.Console.Read();
10.}
In above code when this statement foreach(Account ac in cust.GetAccounts()) is called then acccount list is filled.
Output
Initializing Customer Object
Initialization done
Loading Accounts:
Id:100
Id:101
Id:102
Id:103
Id:104
Id:105
Id:106
Id:107
Id:108
Id:109
Syntax of Lazy<T> object

1.public Lazy();
2.public Lazy(bool isThreadSafe);
3.public Lazy(Func valueFactory);
4.public Lazy(LazyThreadSafetyMode mode);
5.public Lazy(Func valueFactory, bool isThreadSafe);
6.public Lazy(Func valueFactory, LazyThreadSafetyMode mode);
 
Reference:

Design pattern :Inversion of Control & DI fundamentals

In this section we will discuss about how IOC and DI can help us build loosely coupled software architecture. I am not sure should we call this a design pattern or more of a approach. If you search around the web you will see lot of controversy on whether IOC is a design pattern or not. From my point of view it is a design pattern as it solves a problem context.

It would be great to see actual architectures implementing IOC using container oriented approaches. I am sure it will change the way we think about interaction between components.

So let’s understand in detail about IOC and DI.

The Problem – Tight Coupling

Before even we get in to abbreviation of IOC and DIP, let’s first understand the problem. Consider the below example we have a customer class which contains an address class object. The biggest issue with the code is tight coupling between classes. In other words the customer class depends on the address object. So for any reason address class changes it will lead to change and compiling of ‘ClsCustomer’ class also. So let’s put down problems with this approach:

  • The biggest problem is that customer class controls the creation of address object.
  • Address class is directly referenced in the customer class which leads to tight coupling between address and customer objects.
  • Customer class is aware of the address class type. So if we add new address types like home address, office address it will lead to changes in the customer class also as customer class is exposed to the actual address implementation.
     


Figure: - Problems of IOC
So if for any reason the address object is not able to create the whole customer class will fail in the constructor initialization itself.

Solution

Now that we know the issue, let’s understand the solution. The solution definitely revolves around shifting the object creation control from the customer class to some one else. The main problem roots from the customer class creating the address object. If we are able to shift this task / control of object creation from the customer class to some other entity we have solved our problem. In other sentence if we are able to invert this control to a third party we have found our solution. So the solution name is IOC (Inversion of control).

Principles of IOC

The basic principle of IOC stands on the base of Hollywood principle (response given to amateurs auditioning in Hollywood):

Do not call us we will call you 

Translating to bollywood (for struggling actors)

Aap Mauke ko mat bulao, mauka aap ke paas ayega – Hindi conversion ?

In other words it like address class saying to the customer class, do not create me I will create myself using some one else.

There are two principles of IOC:


  • Main classes aggregating other classes should not depend on the direct implementation of the aggregated classes. Both the classes should depend on abstraction. So the customer class should not depend directly on the address class. Both address and customer class should depend on an abstraction either using interface or abstract class.
  • Abstraction should not depend on details, details should depend on abstraction.
     


Figure: - IOC framework
Figure ‘IOC framework’ shows how we can achieve this decoupling. The simplest way would be to expose a method which allows us to set the object. Let the address object creation be delegated to the IOC framework. IOC framework can be a class, client or some kind of IOC container. So it will be two step procedure IOC framework creates the address object and passes this reference to the customer class.

Ways of implementing IOC

Ok, now we know the problem, let’s try to understand the broader level solution. Let’s look at how we implement the solution for IOC. IOC is implemented using DI (Dependency injection). We have discussed on a broader level about how to inject the dependency in the previous sections. In this section we will dive deeper in to other ways of implementing DI.
 



Figure: - IOC and DI
Figure ‘IOC and DI’ shows how IOC and DI are organized. So we can say IOC is a principle while DI is a way of implementing IOC. In DI we have four broader ways of implementing the same:

  • Constructor way
  • Exposing setter and getter
  • Interface implementation
  • Service locator
In the further sections we will walkthrough the same in more detail.

Constructor Methodology

In this methodology we pass the object reference in the constructor itself. So when the client creates the object he passes the object in the constructor while the object is created. This methodology is not suited for client who can only use default constructors.
 



Figure: - Constructor based DI
 

Setter and Getter

This is the most commonly used DI methodology. The dependent objects are exposed through set/get methods of classes. The bad point is because the objects are publicly exposed it breaks the encapsulation rule of object oriented programming.
 



Figure: - Getter and Setter
 

Interface based DI 

In this methodology we implement an interface from the IOC framework. IOC framework will use the interface method to inject the object in the main class. You can see in figure ‘Interface based DI’ we have implemented an interface ‘IAddressDI’ which has a ‘setAddress’ method which sets the address object. This interface is then implemented in the customer class. External client / containers can then use the ‘setAddress’ method to inject the address object in the customer object.
 



Figure: - Interface based DI
 

Service Locator

The other way to inject dependency is by using service locator. Your main class which will aggregate the child object will use the service locator to obtain instance of the address object. The service locator class does not create instances of the address object, it provides a methodology to register and find the services which will help in creating objects.


Figure: - Service locator

Implementing the DI

Now that we know the various types of DI to implement IOC. Its time to understand how we can actually implement these DI’s.  

What’s wrong with DI FACTORY?

The first thing which clicks to mind is, can't we achieve all the above things using factory. The main problem is all about one class doing the creational activity of its contained objects which leads to heavy coupling. Introducing factory can solve that to a great extent.

Here are the issues with factory which makes us force to think about some other solutions:


  • Everything is hardcoded: - The biggest issues with factory are it can not be reused across applications. All the options are hardcoded in the factory itself which makes the factory stringent to particular implementation.
  • Interface dependent: - The base on which factories stands are common interfaces. Interfaces decouple the implementation and the object creation procedure. But then all the classes should implement a common interface. This is a limitation by itself again.
  • Factories are custom: - They are very much custom to a particular implementation.
  • Everything is compile time: - All dependent objects for an object in factory have to be known at compile time.

The container way

A container is an abstraction responsible for object management, instantiation and configuration. So you can configure the objects using the container rather than writing client code like factory patterns to implement object management. There are many containers available which can help us manage dependency injection with ease. So rather than writing huge factory codes container identifies the object dependencies and creates and injects them in appropriate objects.
 



Figure: - Container in action
So you can think about container as a mid man who will register address and customer objects as separate entity and later the container creates the customer and address object and injects the address object in the customer. So you can visualize the high level of abstraction provided by containers.

What we will do is cover the customer and address example using one of the container Windsor container, you can get more details about the container here.


Implementation using Windsor

The first thing we do is create the address interface and create the concrete class from this interface. Interface will be an entity to use for injection rather than concrete objects, so that we deal with more abstraction rather than concrete implementation.
 



Figure: - Address interface
In the customer class we have passed the object through the constructor.


Figure: - Customer class
If we are said to write the client code. , it would be something as shown in figure ‘Client code’. In step 1 we create a concrete object and point the implementation to the interface IAddress. In step 2 we pass the interface object to customer class constructor while creating the object. 


Figure: - Client code
 
Ok, now lets see how this will work if we use the Windsor container. Figure ‘Windsor container’ shows how it looks like. So step 1 creates the Windsor container object. Step 2 and 3 register the types and concrete objects in the container. Step 4 requests the container to create the customer object. In this step the container resolves and set the address object in the constructor. Step 5 releases the customer object.
 



Figure: - Windsor container 
Ok, guys understood, the above code is more complicated than the client code. In actual implementation using the container we never use client code, rather we use config files. You can see from figure ‘Creating using config files’ we have better flexibility to add more objects. The XmlInterpreter object helps to read the config file to register the objects in the container. Using the container.resolve method we have finally created the customer object. So the container plays the mediator role of understanding the customer object and then injecting the address object in the customer object through the constructor. In config file we need to define all the components in the components section.
 



Figure: - Creating using config files