Friday, August 24, 2007
Template Method : template for execution
a new pattern today :)
scenario:
i have some classes to create pizzas (back to pizzas eh!! :) ). my cousin baked some pizzas at my place,so i do know the steps :).
so the steps are
1) use the pizza base.
2) Add toppings.
3) add sauce
4) bake
So now i have an interface IPizza:
public Interface IPizzaManufacture
{
void UsePizzaBase();
void AddToppings();
void AddSauce();
void Bake();
void createpizza ();
}
now the Pizza manufacture classes implement this interface
public Class LargeCheesePizzaManufacture :IPizzamanufacture
{
public void UsePizzaBase
{
Console.Writeline("Using a large Pizza Base");
}
public void AddSauce
{
Console.Writeline("Add Tomato sauce");
}
public void AddToppings
{
Console.Writeline("Cheese Toppings");
}
public void bake()
{
console.WriteLine("Baking now");
}
}
now if i add another class called largePapperoniPizza, i will have to implement all the methods.
nothing wrong with this.
but i notice that i will have to implement the createpizza method for every class i add, even though i dont want to introduce any new createpizza behaviour.
so 20 classes added, 20 times i implement the createpizza() method. can we avoid this?
absolutely yes:
find out the method which will remain common --now it is createpizza().
we will change the interface to an abstract Class
public Abstract Class IPizzaManufacture
{
public abstract void UsePizzaBase();
public abstract void AddToppings();
public abstract void AddSauce();
public abstract void Bake();
public virtual void CreatePizza()
{
UsePizzaBase();
AddToppings();
AddSauce();
Bake();
}
}
now i will implement this abstract class in many other classes.
public Class LargeCheesePizzaManufacture :IPizzamanufacture
{
public override void UsePizzaBase
{
Console.Writeline("Using a large Pizza Base");
}
public override void AddSauce
{
Console.Writeline("Add Tomato sauce");
}
public override void AddToppings
{
Console.Writeline("Cheese Toppings");
}
//no bake method here
//i will use the createpizza method of the abstract class
}
but notice that i will not have to implement the createpizza () method unless i want to add a custom createpizza () functionality.
public Class LargeVegetablePizzaManufacture :IPizzamanufacture
{
public override void UsePizzaBase
{
Console.Writeline("Using a large Pizza Base");
}
public override void AddSauce
{
Console.Writeline("Add Tomato and garlic sauce");
}
public override void AddToppings
{
Console.Writeline("Vegetable Toppings");
}
//i will use the a custom createpizza mechanism
public override void createpizza ()
{
Console.writeLine("createpizza for a long time");
}
}
so the createpizza () method acts as a template.
this is known as Template method because this method will create a template for execution.
happy coding !!!
Wednesday, August 22, 2007
Iterator pattern
long time since my last post :( sorry.
today i will be discussing about a new pattern
scenario :
i want to list all the cars and two wheelers in my locality.i have two classes "cars" and "bikes". but instead of cosing for these classes, i have asked two of my friends to code. they have done a commendable job,everything implemented and works properly. but now, the problem is one of the classes return the list in the form of an arraylist and the other in the form of array.
example :
public arraylist GetCars()
and
public object[] GetBikes()
my friends have given me their code. i have to use it. i will have a difficulty using them cause i will have to use arraylist in one instance and object[] in another. For arraylist, i can use foreach, but for array, i will have to use for loop.
if both of them were somewhat similar, i could have used a generic function to get the objects from the list. But lets get back to reality, both of them are different. how do i manage? do i change the arraylist in one of the classes to array type so that i can use the generic method? or do i change the array to arraylist?
let us think - is it really necessary to change the data structure used to store the data? is it not a complicated change? i really do not know the logic which my friends have used.
is there any other possibility?
yes, there is!!!
the Iterator pattern is the answer.
i will have an interface called iIterator which looks like this
public interface iIterator
{
bool MoveNext();
object getCurrent();
}
and the classes car and twowheeler impements this interface.
MoveNext() will return true/false based on whether the array / arraylist has an object in the next position and moves the cursor to the next position.
getCurrent() will return an object from the current cursor location.
what i did was instead of returning the arraylist/array from the class, i return each individual object and then move the cursor to the next location.
this will be clear if we look into the example for the class which has arraylist.
public class Cars : iIterator
{
private int Cursor = 0;
Arraylist Cars = new Arraylist();
//-----------------------------------------
//the code for filling up the arraylist goes here
//lets not get into it as we are aware of how this is done
------------------------------------------//
public object getCurrent()
{
return arraylist[Cursor];
}
public bool MoveNext()
{
Cursor+=1;
}
}
the same will be done for any other data structure used for storage like array,list etc.
hope this article helps you.
happy coding !!!!
Wednesday, August 15, 2007
Test driven development in dot net using NUnit - part1
I am back with another post today.
we will be discussing about Test Driven Development (TDD).
well the first question is What is TDD?
TDD is the process of developing a software so that the unit testing of the code can be done using some tools (like NUnit or JUnit).
so if use TDD do we have to test in the whole software delivered to the customer ?
YES, we will have to test the whole component after the software is developed.This test will be done to assure that the software is working as per expectations.
but what we must understand is that a software is as good as its individual components.If one of the components of a software is not working fine,then the whole system fails.
a set of classes constitute a component. class will have a set of functions. so we write classes and functions and then we use TDD to test these functions. This assures us that the minute parts of the system are working fine.
but we will have to follow some Object Oriented guidelines for using TDD:
1) we should eliminate the duplication of code. i mean to say that a function should not be repeated elsewhere in the particular component. This assures us of optimal reuse.So we should make sure that classes do not have common methods.
2) if an operation is being performed in several different places, then it is better to create a function for this operation and call that function.
Reason : let us consider a scenario where we are doing a string comparison in several different places.example
str.ToUpper()==str2.ToUpper().
now at a later point of time i realize that i have to change this, then i will have to make the changes at several different places where i am doing this operation.
3) Every operation or action being performed should be broken down in to a single individual function so that it will be easy to test that particular functionality.
example :
factorial of 5 = 5*4*3*2*1 = 120
we do code for this as
public int factorial(int num)
{
int result =1;
while (num>1)
{
result = result * num;
num= num-1;
}
return result;
}
but now if the factorial function for 5 returns 60 instead of 120,what may be the reason?
we will have to debug and find out.
if there any other way?can we just see the test results and ascertain where it fails?
can we make this more testable?
yes, we can create two new functions -for multiply and then subtract.
public int factorial(int num)
{
int result =1;
while (num>1)
{
result = multiply(result,num);
num= subtract(num,1);
}
}
public int Multiply(int num1,int num2)
{
return num1* num2;
}
public int Subtract(int num1,int num2)
{
return num1-num2;
}
so now it becomes easy for us to test the factorial functionality. the advantage being if the factorial function is not giving the expected results, then we can find out where it fails by the tests for multiply and subtract functions.
in my next post, we can discuss how to use NUnit for testing.
Sunday, August 5, 2007
Adapter Pattern : adapt your interfaces
hi,
oen of the problems which i faced while developing some component was with arraylist. This arraylist is present in System.Collections namespace. teh problem which i faced was that, i had created an arraylist to hold a particular interface (say for my game , it would be ICar interface). now i add objects of type car here into the arraylist, and while retrieving objects from the arraylist, i type cats it to ICar. it works fine. but a new requirement arises and we have to keep track of a new interface IPlane in the arraylist. so, while retrieving , i will have to typecast the object to ICar and if an exception is thrown, catch it and typecast the same object to IPlane. this is not proper code, why? because tomorrow, if i want to add a new interface IShip to Arraylist, ihaev to catch another exception and then typecast it to IShip? exactly, then my code will be filled with only try catch block in a nested format. But wher did i go wrong in the design? i had a n interface, i did the best possible design. yes, until here, i have done the best possible design.but where i went wrong was directly adding the object which implement IPlane interface to the arraylist. This caused confusion between ICar and IPlane in the arraylist while retrieving. yes i do have a solution for this problem. we have to wrap the Plane Object in someother class. Also this wrapper for IPlane whould conform to ICar interface...confusing? in simple terms, we introduce a new class which composes of IPlane and implements ICar. This is the Adapter Class. this Adapts IPlane to conform to ICar.
See the code below :
using System;
using System.Collections.Generic;
using System.Text;
namespace FactoryPattern
{
public interface ICar
{
//some properties here
}
class Audi : ICar
{
public Audi()
{
}
//implemnt the interface here
}
class Benz : ICar
{
public Benz()
{
}
//implemnt the interface here
}
public class CarFactory
{
public CarFactory()
{
}
}
I have an arraylist wher in i add CarObjects,
ArrayList transportVehicles = new ArrayList();
transportVehicles.Add((ICar)new Car());
for (int i = 0; i < transportVehicles.Count; i++)
{
ICar car = (ICar)transportVehicles[i];
car.Move();
}
Now i introduce a new mode of tranport- a plane (it flies instead of moving on land).
ArrayList transportVehicles = new ArrayList();
transportVehicles.Add((ICar)new Car());
transportVehicles.Add((IPlane)new Plane());
for (int i = 0; i < transportVehicles.Count; i++)
{
ICar car = (ICar)transportVehicles[i];
car.Move();
}
Then iwll get an exception, coz the second object in the arraylist is of type IPlane and it cannot be typecasted to ICar.
So now i introduce another class called the Adapter which Adapts the Iplane interface to ICar interface
public class PlaneAdapter : ICar
{
IPlane plane;
public PlaneAdapter(IPlane planeobject)
{
plane = planeobject;
}
public void Move()
{
plane.Fly();
}
}
And then change the method of invoking to
ArrayList transportVehicles = new ArrayList();
transportVehicles.Add((ICar)new Car());
transportVehicles.Add((ICar)new PlaneAdapter((IPlane)new Plane())); // notice the change here
//Plane adapter implements ICar, so we can type cats PlaneAdapter to ICar
for (int i = 0; i < transportVehicles.Count; i++)
{
ICar car = (ICar)transportVehicles[i];
car.Move();
}
Now there will be no exception and also teh output will be
car is moving
The plane is flying
All I did was to introduce another class which implemented ICar and composed IPlane. This worked like magic for me!! hope this will help you too.
Happy Coding!!!
Factory - manufacture objects
hi,
Another post, another pattern !!!!
Scenario :
My good old car racing game. But now the car models have been decided. now i would like to use an Audi and a Benz. So we have a ICar interface which is implemented by two car classes - Audi and Benz.but when i haev to create an instance of the Car class, i will have to pass the car model as parameter. the code will be somewhat like :
if(CarModel == ECarModel.AUDI) // ECarModel is an enum
{
return new Audi();
}
else if(CarModel ==ECarModel.BENZ)
{
return new Benz();
}
This code will be used whenever i want to create an instance of a car. i would create a instance of car for many scenarios like : car upgrade, new car bought, new car won as an award etc. so i will have to replicate this code snippet everywhere. now i want to enhance my game i want to include a few more models like Diablo. Does it mean i have to change the code snippet where ever it is present? yes, of course,i will have to do it. hey , what if i make changes to the existing design itself so that i can accomodate any future enhancements? yes, i need to do it. HOW? i will introduce a new class which deals with creating instances for the cars. this class will be called as CarFactory. it deals only with creating instances of Car class- that is the only purpose of the class. so next time any new car is introduced, i need to change this factory class.
Code is as given below :
using System;
using System.Collections.Generic;
using System.Text;
namespace FactoryPattern
{
public interface ICar
{
//some methods for the car like move(),break(),spo(),increaseGear(),DecreaseGear() here
}
class Audi : ICar
{
public Audi()
{
}
//implemnt the interface here
}
class Benz : ICar
{
public Benz()
{
}
//implemnt the interface here
}
public class CarFactory
{
public CarFactory()
{
}
public ICar createCar(string Cartype) // instead of a string i can also pass an enum here
{
if (Cartype == "Audi")
{
return new Audi();
}
if (Cartype == "benz")
{
return new Benz();
}
else
return null;
}
}
}
this is the factory pattern!!! the responsibility of creating the class is handed over to the factory for that class.
Happy coding !!!
State pattern : states as objects
Hi,
i am back with another post.This time it is a new pattern - State Pattern. Consider this scenario : i want to develop a car racing Game. so i have the Car class with ICar interface. i have to increase or decrease the gear in the car so, i have the same methods in the interface. i have an enum for all the gears. as of now, the car has only two gears. so the enum will have two entries - neutral and first gear. the car class implements the IncreaseGear() function
void ICar.IncreaseGear()
{
if (State == GearState.Neutral)
{
State = GearState.FirstGear;
}
}
this is the code for the whole game as of now:
using System;
using System.Collections.Generic;
using System.Text;
namespace StatePattern
{
enum GearState
{
Neutral = 0,
FirstGear =1
}
interface ICar
{
void IncreaseGear();
void DecreaseGear();
}
class Car : ICar
{
GearState State = GearState.Neutral;
public Car()
{
State = GearState.Neutral;
}
#region ICar Members
void ICar.IncreaseGear()
{
if (State == GearState.Neutral)
{
State = GearState.FirstGear;
}
if (State == GearState.FirstGear)
{
//Do nothing
}
}
//this will be implemented later on
void ICar.DecreaseGear()
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
}
one - in the enum
two - in the IncreaseGear() function, i will have to put one more if condition
three - in the DecreaseGear() function, i will have to put one more if condition.
thats is ok as i feel that the changes are minimal.
A few days later, i want my car to upgrade and then i introduce a third gear.
again will have to make changes everywhere.
somehow i feel very uncomfortable here. then i think whether there is another way wherein i can make it more flexible and open to enhancement. yes of course, there is a way.
we can treat every individual gear as a state (nothing but another class) and then let the state itself handle what it wants to do.
so we will have a GearState interface. all gears (neutral, first , second etc) implement this interface. The car class composes of the GearState as a member. Car class implements ICar in such a way that it calls the GearState's Increase and Decrease function for the ICar's methods.
Code is as given below :
using System;
using System.Collections.Generic;
using System.Text;
namespace StatePattern
{
interface GearState
{
GearState Increase();
GearState Decrease();
}
public class FirstGear : GearState
{
public FirstGear()
{
}
#region GearState Members
public GearState Increase()
{
Console.WriteLine("first Gear");
return this;
}
public GearState Decrease()
{
Console.WriteLine("reducing the gear state to neutral");
return new Neutral();
}
#endregion
}
public class Neutral : GearState
{
public Neutral()
{
}
#region GearState Members
public GearState Increase()
{
Console.WriteLine("Increasing to First Gear");
return new FirstGear();
}
public GearState Decrease()
{
Console.WriteLine("Cannot decrease Further,already in neutral");
return this;
}
#endregion
}
interface ICar
{
void IncreaseGear();
void DecreaseGear();
}
class Car : ICar
{
GearState State;
public Car()
{
State = new Neutral();
}
#region ICar Members
public void IncreaseGear()
{
State.Increase();
}
public void DecreaseGear()
{
State.Decrease();
}
#endregion
}
}
now if i want to introduce a new gear, i just implement the GearState interface and then implement the functions for increase and decrease. and in the FirstGear class, retru nan instance of SecondGear in the increase Function.
notice how flexible and simple this is.
Happy coding !!!!!
regards,
nandan