Abstract Factory and Proxy design patterns

Abstract Factory

I have many individual types and those types will be used by some other types. For the consumer types, it has to know about all the individual types, so instead of doing this, we can create a medium by which consumer can access all the individual types. For example, I have typeA, typeB and typeC, so instead of consumer create objects of all those types, if we used Abstract Factory pattern then we can used a new factory types with facility like CreateTypeA(),  CreateTypeB(), CreateTypeC() method which will return relevant objects. For details we will go through the example below,

Following class diagram will give the picture of the abstract factory pattern example project.


Fig: Abstract Factory Pattern class diagram.

and the project structure in Visual studio,



Fig: Project structure of the Abstract Factory design pattern.
Source code of the projects:

Factory class of AbstractFactory project - this class exposes two methods to the consumers.

namespace AbstractFacotry
{
    using BaseClassDefinition;
    using BaseClassImplementation;
 
    public class Factory
    {
        public ProductABaseClass CreateProductA()
        {
            return new ProductA();
        }
        public ProductBBaseClass CreateProductB()
        {
            return new ProductB();
        }
    }
}


ProductABaseClass and ProductBBaseClass of BaseClassDefinition - following classes define the definition of the concrete class.

namespace BaseClassDefinition
{

    public abstract class ProductABaseClass
    {
        public abstract int GetProductAPrice();
    }
}
namespace BaseClassDefinition
{
    public abstract class ProductBBaseClass
    {
        public abstract int GetProductBPrice();
    }
}


ProductA and ProductB of BaseClassImplementation project - ProductA and ProductB class is the implementation of the BaseClassImplementation.

namespace BaseClassImplementation
{
    using BaseClassDefinition;
    public class ProductA : ProductABaseClass
    {
 
        public override int GetProductAPrice()
        {
            return 1;
        }
    }
}

namespace BaseClassImplementation
{
    using BaseClassDefinition;
    public class ProductB : ProductBBaseClass
    {
        public override int GetProductBPrice()
        {
            return 2;
        }
    }
}


Program class of TestHarness project - this test harness will use the Factory class to instantiate the concrete classes for example in ProductA and ProductB via Factory class.

namespace TestHarness
{
    using System;
    using AbstractFacotry;
    using BaseClassDefinition;
 
    class Program
    {
        static void Main(string[] args)
        {
            ProductABaseClass childOneOfBaseClass = new Factory().CreateProductA();
            ProductBBaseClass childTwoOfBaseClass = new Factory().CreateProductB();
 
            Console.WriteLine("{0}", childOneOfBaseClass.GetProductAPrice());
            Console.WriteLine("{0}", childTwoOfBaseClass.GetProductBPrice());
        }
    }
}
 

Output of the above Test Harness program is as below,

1
2
Press any key to continue . . .


Proxy Pattern

It provides a way to access real object via another types. If we see the Service References of WCF application then we will find a real example of Proxy Pattern. 

See the below class diagram for Proxy Pattern project,


Fig: Class diagram of Proxy pattern project.
and  project structure of the proxy pattern



Fig: Project structure of the Proxy Pattern
AbstractProduct class of ProxyPattern-BaseClassDefiition project - base type of all the children.

namespace ProxyPattern_BaseClassDefinition
{
    public abstract class AbstractProduct
    {
        public abstract string GetProductName();
    }
}


ProductA class of ProxyPattern-BaseClassImplementation - Implementation of base class.

namespace ProxyPattern_BaseClassImplementation
{
    using ProxyPattern_BaseClassDefinition;
    public class ProductA : AbstractProduct
    {
        public override string GetProductName()
        {
            return "Product A";
        }
    }
}


Proxy_ProductA class of ProxyPattern-Proxy project - a proxy of ProductA class.

namespace ProxyPattern_Proxy
{
    using ProxyPattern_BaseClassDefinition;
    using ProxyPattern_BaseClassImplementation;
    public class Proxy_ProductA : AbstractProduct
    {
        private ProductA productA;
        public override string GetProductName()
        {
            if (productA == null)
                productA = new ProductA();
            return productA.GetProductName();
        }
    }
}


Program class of ProxyPattern-TestHarness where I use Proxy class Proxy_ProductA to access the real object which is ProductA.

namespace ProxyPattern_TestHarness
{
    using System;
    using ProxyPattern_Proxy;
    class Program
    {
        static void Main(string[] args)
        {
            Proxy_ProductA proxy = new Proxy_ProductA();
            Console.WriteLine("{0}", proxy.GetProductName());
        }
    }
}


The output of the Test harness is as below,

Product A
Press any key to continue . . .


Note:

always happy to learn from others and happy to get new ideas. thanks. mohammad

 Few C# and Application Design books from Amazon,

Lambda Expression in C#

I think most of .Net coder is familiar with Lambda expression. So it is basically a way to write anonymous function. According to the syntax Lambda expression can take Input and based on the Input and expression it will produce the output. The syntax of the Lambda expression is

(input parameters) => expression or statements.

For example if I have a method with the following body

int Add( int a, int b ){
      return a+b;
}
to
(a,b)=>{ return a+b; } with the contract Func<int, int>. So it will be like below,
Func<int, int> add = (a,b)=>{return a+b;}


There are lots of interesting thing about Lambda expression and Extension methods. In this article I discuss about few stuffs about Lambda and Func then do something with the Extension methods Select and Where of IEnumerable class.

The example of I am to use in this article will have basic lambda and Func along with these there will be IEnumerable class with Select and Where extension methods. In the example Program class will have few basic things about Lambda and Calculator class has few other stuff. I include the code in one chunk.

namespace TestHarness
{
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using System.Collections;
    class Program
    {
        static void Main(string[] args)
        {
            Action<int> printer = (x) => Console.Write("{0}\t", x);
 
            Func<intintint> funcAdd = (x1, x2) => { return (x1 + x2); };
            Func<intintint> funcAddExtraLogic =
                (x1, x2) =>
                {
                    if (x1 > x2)
                        x1 = x1 * 2;
                    else
                        x2 = x2 * 2;
                    return (x1 + x2);
                };
 
            Console.WriteLine("Lamda expression test: \t{0}", funcAdd(4, 4));
            Console.WriteLine("Lambda expression test:\t{0}", funcAddExtraLogic(4, 4));
 
            Calculator calculator = new Calculator();
            Console.WriteLine("{0}", calculator.Add(4, 4));
            Console.WriteLine("{0}", calculator.Add(calculator.AddImplementator(), 4, 4));
            Console.WriteLine("{0}", calculator.AddImplementator()(4, 4));
 
            Console.WriteLine("Get the list:");
            Console.WriteLine("Using Lambda exrepession.");
            calculator.GetResultUsingExpression().ToList<int>().ForEach(printer);
            Console.WriteLine("Using Lambda exrepession with Func method.");
            calculator.GetResult().ToList<int>().ForEach(printer);
            Console.WriteLine("Using Lambda exrepession with inline delegate implementation");
            calculator.GetResult(x => { return x % 2 == 0; }, x => { return x; }).ToList<int>().ForEach(printer);
 
        }
    }
    public class Calculator
    {
        Func<intintint> mFuncAdd = (x1, x2) => { return (x1 + x2); };
 
        public int Add(int a, int b)
        {
            return mFuncAdd(a, b);
        }
        public int Add(Func<intintint> funcAdd, int a, int b)
        {
            return funcAdd(a, b);
        }
 
        public Func<intintint> AddImplementator()
        {
            return (a, b) =>
            {
                return a + b;
            };
        }
 
        public IEnumerable<int> GetResultUsingExpression()
        {
            int u = 40;
            IEnumerable<int> result = Enumerable
                .Range(0, 100)
                .Where(x => x % 2 == 0 && x > u)
                .Select((x) => x * 2);
            return result;
        }
 
        public IEnumerable<int> GetResult()
        {
            int u = 40;
            IEnumerable<int> result = Enumerable
                .Range(0, 100)
                .Where(x => Check()(x, u))
                .Select((x) => SelectCondition()(x));
            return result;
        }
 
        public IEnumerable<int> GetResult(Func<intbool> checker, Func<intint> selector)
        {
            IEnumerable<int> result = Enumerable
                .Range(0, 100)
                .Where(x => checker(x))
                .Select((x) => selector(x));
            return result;
        }
 
        private Func<intintbool> Check()
        {
            return (int a, int u) =>
            {
                return a % 2 == 0 && a > u;
            };
        }
 
        private Func<intint> SelectCondition()
        {
            return (a) =>
            {
                return a * 2;
            };
        }
    }
}



In the above code I create a delegate Func<int, int,int> funcAdd and  this (x1,x2)=>{return (x1+x2);} anonymous method using Lambda expression. and there is also another delegate named funcAddExtraLogic. I created this one to show how can I use multiple statements.


In the Calculator class I implement few methods to manipulate a list to show the usage of Where and Select extension methods. Where and Select methods have the following signature,

public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source,Func<TSource, bool> predicate)

public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source,Func<TSource, TResult> selector)


Following methods manipulate the list using Where and Select. As the signature shows it is extension methods of the IEnumerable and as well it accept a Func with TSource as input parameter and bool as output parameter. From the beginning of this article I showed Func is a  anonymous function, so it uses x=>x%2==0 &&x>u.
public IEnumerable<int> GetResultUsingExpression()
        {
            int u = 40;
            IEnumerable<int> result = Enumerable
                .Range(0, 100)
                .Where(x => x % 2 == 0 && x > u)
                .Select((x) => x * 2);
            return result;
        }



on the other hand as Where accept a Func<int, bool> delegate so I implement a method with return type Func<int, bool> and then use that for Where. So the code is as below,

public IEnumerable<int> GetResult()
        {
            int u = 40;
            IEnumerable<int> result = Enumerable
                .Range(0, 100)
                .Where(x => Check()(x, u))
                .Select((x) => SelectCondition()(x));
            return result;
        }


private Func<intintbool> Check()
        {
            return (int a, int u) =>
            {
                return a % 2 == 0 && a > u;
            };
        }




The output of the example is as below,

Lamda expression test:  8
Lambda expression test: 12
8
8
8
Get the list:
Using Lambda exrepession.
84      88      92      96      100     104     108     112     116     120
124     128     132     136     140     144     148     152     156     160
164     168     172     176     180     184     188     192     196     Using La
mbda exrepession with Func method.
84      88      92      96      100     104     108     112     116     120
124     128     132     136     140     144     148     152     156     160
164     168     172     176     180     184     188     192     196     Using La
mbda exrepession with inline delegate implementation
0       2       4       6       8       10      12      14      16      18
20      22      24      26      28      30      32      34      36      38
40      42      44      46      48      50      52      54      56      58
60      62      64      66      68      70      72      74      76      78
80      82      84      86      88      90      92      94      96      98
Press any key to continue . . .


happy to learn from others.

Thanks
mohammad

Refactoring - improve the code and make it understandable - Part 1

A coder can write code, it will work and will do the job. So writing a code would be pretty straight forward. I found many coder, after finishing their code they want to optimize the code. Then the concept comes REFACTORING.

Now a days many IDEs for example Microsoft Visual Studio 2010 support Refactoring. So it will refactor the code on behalf of the  coder by clicking few options.  For example, in VS 2010 if we click on the Refactor menu item we will see the following menu items:


Refactor
  • Rename
  • Extract Method..
  • Encapsulate Field...
  • Extract Interface...
  • Remove Parameters...
  • Reorder Parameters....

as well as there are many books in regards to the refactoring. I like the book named, Refactoring: Improving the Design of Existing Code by Martin Fowler. I think if we get chance we should read this book.

In this article I am going to write few refactoring methods.

Extract Class - Refactoring
The main objective of this refactoring is related members from one class to another independent class. In this following example Person class has Name, OfficeAreaCode and OfficeNumber. Using this extract class refactoring strategy I am going to move  OfficeAreaCode and OfficeNumber members from Person class to TelephoneNumber class. If we see the class diagram then perhaps it would be more clear.


Fig: Extract class.

Person class before refactoring,

namespace RefactoryExampleLibrary.ExtractClass
{
    public class Person
    {
        public string Name { getset; }
        public string OfficeAreaCode { getset; }
        public string OfficeNumber { getset; }
 
        public Person() { }
 
        public string GetTelephoneNumber()
        {
            return string.Concat(new[] { OfficeAreaCode, OfficeNumber });
        }        
    }
}


After applying the Extract class Refactoring method Person class has been divided into two separate classes.

namespace RefactoryExampleLibrary.ExtractClass
{
    public class PersonAfter
    {
        public string Name { getset; }
        public TelephoneNumber officeNumber;
 
        public PersonAfter()
        {
            officeNumber = new TelephoneNumber();
        }
        public string GetTelephoneNumber()
        {
            return officeNumber.GetTelephoneNumber();
        }
    }
}

namespace RefactoryExampleLibrary.ExtractClass
{
    public class TelephoneNumber
    {
        public string OfficeAreaCode { getset; }
        public string OfficeNumber { getset; }
 
        public TelephoneNumber() { }
 
        public string GetTelephoneNumber()
        {
            return string.Concat(new[] { OfficeAreaCode, OfficeNumber });
        }
 
    }
}




The test class Program will test the above code.

namespace Refactoring_TestHarness
{
    using System;
    using RefactoryExampleLibrary.ExtractClass;
 
    class Program
    {
        static void Main(string[] args)
        {
 
            Person person = new Person()
            {
                Name = "A",
                OfficeAreaCode = "02",
                OfficeNumber = "1111"
            };
            Console.WriteLine("{0}", person.GetTelephoneNumber());
 
            PersonAfter personAfter = new PersonAfter()
            {
                Name = "A",
                officeNumber = new TelephoneNumber()
                {
                    OfficeAreaCode = "02",
                    OfficeNumber = "1111"
                }
            };
}


The output of the above code will exactly same as below,

021111
021111
Press any key to continue . . .


Introduce Parameter Object - Refactoring
The motive of this method is to reduce long parameter list from a class method. For example following GetDateOfBirth method of IntroduceParameterObject is taking three parameter for instance, day, month, year. So instead of passing three parameter we could reduce this to one parameter by implementing one type class such as DobComponents in here.
end code
namespace RefactoryExampleLibrary.IntroduceParameterObject
{
    public class IntroduceParameterObject
    {
        public IntroduceParameterObject() { }
 
        public string GetDateOfBirth(string day, string month, string year)
        {
            string[] dobComponents = { day, month, year };
            return string.Join("/", dobComponents);
        }
        public string GetDateOfBirth(DobComponents components)
        {
            string[] dobComponents = { components.Day, components.Month, components.Year };
            return string.Join("/", dobComponents);
        }
    }
 
    public class DobComponents
    {
        public string Day { getset; }
        public string Month { getset; }
        public string Year { getset; }
 
        public DobComponents() { }
    }
}

namespace Refactoring_TestHarness
{
    using System;
    using RefactoryExampleLibrary.ExtractClass;
    using RefactoryExampleLibrary.IntroduceParameterObject;
 
    class Program
    {
        static void Main(string[] args)
        {
            IntroduceParameterObject introduceParameterObject = new IntroduceParameterObject();
            Console.WriteLine("IntroduceParameterObject output,");
            Console.WriteLine("{0}", introduceParameterObject.GetDateOfBirth("01""01""0000"));
            Console.WriteLine("{0}", introduceParameterObject.GetDateOfBirth(new DobComponents() { Day = "01", Month = "01", Year = "0000" }));
}
}


The output of the class is as below,

IntroduceParameterObject output,
01/01/0000
01/01/0000
Press any key to continue . . .


Preserve Whole Object - Refactoring
This sort of refactoring reduce local variable dependency of the data and as well delegate the responsibility to the relevant type. In this example, CheckDateRangeWithoutPReserveObject method use Temperature type to get High and Low temperature by storing locally by declaring high and low local variable. Instead of doing this, leave the responsibility to the relevant method to access value. For instance, in here I implement a method name TemperatureWithDays with input parameter type Temperature so then this method can directly access high and low value from the Temperature object. 

namespace RefactoryExampleLibrary.PreserveWholeObject
{
    using System;
    public class PreserveWholeObject
    {
        public PreserveWholeObject() { }
        /*
         * Before Preserve Whole Object
         */
        public bool CheckDateRangeWithoutPreserveWholeObject()
        {
            Temperature temperature = new Temperature();
            int high = temperature.GetHigh();
            int low = temperature.GetLow();
 
            return new DaysTemperature().TemperatureWithDays(high, low);
        }
        /*
         * After Preserve Whole Object
         */
        public bool CheckDateRangePreserveWholeObject()
        {
            return new DaysTemperature().TemperatureWithDays(new Temperature());
        }
    }
 
    internal class DaysTemperature
    {
        public int todayTemperature = 250;
        public DaysTemperature() { }
 
        public bool TemperatureWithDays(int high, int low)
        {
            return (todayTemperature < high && todayTemperature > low);         
        }
 
        public bool TemperatureWithDays(Temperature temperature)
        {
            return (todayTemperature < temperature.GetHigh() && todayTemperature > temperature.GetLow());
        }
    }
 
    internal class Temperature
    {
        public Temperature() { }
 
        public int GetHigh()
        {
            return Int16.MaxValue;
        }
 
        public int GetLow()
        {
            return Int16.MinValue;
        }
    }
}

namespace Refactoring_TestHarness
{
    using System;
    using RefactoryExampleLibrary.PreserveWholeObject;
 
    class Program
    {
        static void Main(string[] args)
        {

            PreserveWholeObject preserveWholeObject = new PreserveWholeObject();
            Console.WriteLine("PreserveWholeObject output:");
            Console.WriteLine("{0}", preserveWholeObject.CheckDateRangeWithoutPreserveWholeObject());
            Console.WriteLine("{0}", preserveWholeObject.CheckDateRangePreserveWholeObject());
        }
}


The output of above code will be as below,

PreserveWholeObject output:
True
True
Press any key to continue . . .


Replace method with method object - Refactoring
Again in here the whole concept is to de-couple logic to the relevant type instead of having in the caller. In this example, I extract the computation logic from the Gamma method's to the Gamma class and call this new compute method of Gamma class from Gamma method.

namespace RefactoryExampleLibrary.ReplaceMethodwithMethodObject
{
    using System;
    public class ReplaceMethodwithMethodObject
    {
        public ReplaceMethodwithMethodObject() { }
 
        public int ComputeGamma()
        {
            return new Account().Gamma(1, 1, 1);
        }
 
        public int ComputeGammaRefactored()
        {
            return new Account_Refactored().Gamma(1, 1, 1);
        }
    }
 
    /*
     * Before Refactoring
     */
    public class Account
    {
        public Account() { }
        public int Gamma(int inputVal, int quantity, int yearToDate)
        {
            int importantValue1 = (inputVal * quantity) + delta();
            int importantValue2 = (inputVal * yearToDate) + 100;
 
            if ((yearToDate - importantValue1) > 100)
                importantValue2 -= 20;
 
            int importantValue3 = importantValue2 * 7;
            // and so on.
            return importantValue3 - 2 * importantValue1;
        }
 
        public int delta()
        {
            return 1;
        }
    }
    /*
     * After Refactoring
     */
 
    public class Account_Refactored
    {
        public int Gamma(int inputVal, int quantity, int yearToDate)
        {
            return new Gamma(this, inputVal, quantity, yearToDate).Compute();
        }
 
        public int delta()
        {
            return 1;
        }
    }
 
 
    public class Gamma
    {
        private Account_Refactored account;
        private int inputVal, quantity, yearToDate;
        private int importantValue1, importantValue2, importantValue3;
 
        public Gamma(Account_Refactored accountSource, int inputValArgs, int quantityArgs, int yearToDateArgs)
        {
            account = accountSource;
            inputVal = inputValArgs;
            quantity = quantityArgs;
            yearToDate = yearToDateArgs;
        }
 
        public int Compute()
        {
            int importantValue1 = (inputVal * quantity) + account.delta();
            int importantValue2 = (inputVal * yearToDate) + 100;
            if ((yearToDate - importantValue1) > 100)
                importantValue2 -= 20;
            int importantValue3 = importantValue2 * 7;
            // and so on.
            return importantValue3 - 2 * importantValue1;
        }
    }
}

namespace Refactoring_TestHarness
{
    using System;
    using RefactoryExampleLibrary.ReplaceMethodwithMethodObject;
 
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Replace method with method object");
            ReplaceMethodwithMethodObject replaceMethodwithMethodObject = new ReplaceMethodwithMethodObject();
            Console.WriteLine("{0}", replaceMethodwithMethodObject.ComputeGamma());
            Console.WriteLine("{0}", replaceMethodwithMethodObject.ComputeGammaRefactored());
        }
    }
}

The output of the above program is as below,

Replace method with method object
703
703
Press any key to continue . . .


Split temporary variable - Refactoring
I think this is  pretty good method to make code more understandable for other coder. For example in here, following code is less understandable 
long temp = Quantity * Price * 2;
temp = Quantity * temp; 


compare to  
long area = Quantity * Price * 2;
long length = Quantity * area;

I used following code to implement the concept,

namespace RefactoryExampleLibrary.SplitTemporaryVariable
{
    public class SplitTemporaryVariable
    {
        private long quantity = 10;
        private long price = 11;
 
        public SplitTemporaryVariable() { }
        /*
         * Before implementing the Split Temporary variables.
         */
        public long SplitTemporaryVariableBefore() {
            long temp = Quantity * Price * 2;
            temp = Quantity * temp; 
            return temp;
        }
        /*
         * After implementing the Split Temporary variables.
         */
        public long SplitTemporaryVariableAfter()
        {
            long area = Quantity * Price * 2;
            long length = Quantity * area;
            return length;
        }
 
        public long Quantity
        {
            get { return quantity; }
            set { quantity = value; }
        }
        public long Price
        {
            get { return price; }
            set { price = value; }
        }
    }
}


and following code to test the SplitTemporaryVariable,
namespace Refactoring_TestHarness
{
    using RefactoryExampleLibrary.SplitTemporaryVariable;
    using System;
 
    class Program
    {
        static void Main(string[] args)
        {
            SplitTemporaryVariable splitTemporaryVariable = new SplitTemporaryVariable();
            Console.WriteLine("Split Temporary Variable");
            Console.WriteLine("{0}",splitTemporaryVariable.SplitTemporaryVariableBefore());
            Console.WriteLine("{0}", splitTemporaryVariable.SplitTemporaryVariableAfter());
        }
    }
}


The output of the above code is as below,

Split Temporary Variable
110
110
Press any key to continue . . .



I will discuss about some other refactoring methods on part 2 of this article.

Happy to learn from others.

Thanks
mohammad

 Few C# and Application Design books from Amazon,