hi,
am back after a long time :)
today its a new design pattern.
scenario
i want to design a graphic engine which has a graphic surface and this surface renders many graphic images like lines,rectangles etc.
so where do we start?
we will have an interface IGraphic (methods - AddControl,RemoveControl,getControls)
this is implemented by a a class Graphic
public class Graphic :IGraphic
{
//implement the methods here
//also this class will compose of IControl - which are implemented by control class
}
this is fine.....
i am happy and the software works fine.....until one da ,when the customer comes back to me ..he says that he wants controls to host other controls...he wants the graphic surface to host controls and these controls may contain other controls.
so now how will i incorporate this?
am i stuck ?
well as a matter of fact,i am in a litle bit of a soup.
i can somehow manage for the particular control the cutomer says as of now.
but if he comes back tomorrow for another control, i am lost again :(.......
wel lbut now i know of these problems, why not change the intial design itself to incorporate all the changes the customer asks for?
how? have a look below
IGraphic can be an abstract class.
public abstract class IGraphic
{
public void AddChild();
public void RemoveChild();
public arraylist getChildren();
}
public class Graphic :IGraphic
{
//implement the methods of the base class here
//have an arraylist of child objects
//so it will be
arraylist Children;
}
public class GroupBox : IGraphic
{
//implement the methods of the base class
//have an arralist of the children
arraylist children;
}
public class Button:Igraphic
{
//provide dummy implementation here for addchild , getchildren and removechild as
//this control does not have children
}
example code is given below
public abstract class IGraphic
{
protected System.Collections.ArrayList Children;
string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public abstract void AddChild(object obj);
public abstract void removechild(object obj);
public abstract System.Collections.ArrayList getChildren();
public void print()
{
Console.WriteLine("Name is "+Name);
}
}
public class graphic : IGraphic
{
public graphic()
{
Children = new ArrayList();
}
public override void AddChild (object obj)
{
Children.Add(obj);
}
public override void removechild (object obj)
{
Children.Remove(obj);
}
public override System.Collections.ArrayList getChildren()
{
return Children;
}
public void print()
{
Console.WriteLine("Name is "+Name);
foreach(object obj in Children)
{
Console.WriteLine("children are " + ((IGraphic)obj).Name);
}
}
}
public class Groupbox : IGraphic
{
public Groupbox()
{
Children = new ArrayList();
}
public override void AddChild (object obj)
{
Children.Add(obj);
}
public override void removechild (object obj)
{
Children.Remove(obj);
}
public override System.Collections.ArrayList getChildren()
{
return Children;
}
public void print()
{
Console.WriteLine("Name is "+Name);
foreach(object obj in Children)
{
Console.WriteLine("children are " + ((IGraphic)obj).Name);
}
}
}
public class Button : IGraphic
{
public Button()
{
}
public override void AddChild (object obj)
{
//do nothing
}
public override void removechild (object obj)
{
//do nothing
}
public override System.Collections.ArrayList getChildren()
{
//do nothing
return null;
}
public void print()
{
Console.WriteLine("Name is "+Name);
}
}
static void Main(string[] args)
{
graphic g = new graphic();
g.Name = "graphic object";
Groupbox gbox = new Groupbox();
gbox.Name = "Groupbox";
Button b = new Button();
b.Name = "button inside the groupBox";
Button btn = new Button();
btn.Name = "button inside the graphic";
gbox.AddChild(b);
gbox.print();
g.AddChild(gbox);
g.print();
g.AddChild(btn);
btn.print();
g.print();
}
output is
Name is Groupbox
children are button inside the groupBox
Name is graphic object
children are Groupbox
Name is button inside the graphic
Name is graphic object
children are Groupbox
children are button inside the graphic
junkiesntechies
Thursday, December 6, 2007
Tuesday, November 27, 2007
WCF
Windows Communication Foundation? WCF? Waatzeet?
I will discuss about what WCF is a little later on. But now we will have to summarise how two different Applications can interact with each other. We have remoting which allows two different applications in different application domains to interact with each other. We have MSMQ using which two different applications can pass messages between them. We have WebServices using which we can make two applications interact.but all these have some shortcomings. For exampleMSMQ will be able to run on only windows machines.two applications have to conform to some specific standards if they have to use web services. Remoting will be possible only if both the applications are written in dot net.so to over come all these shortcomings, microsoft has come up with a new set of APIs to enable communication. This is Windows Communication Framework.
This is similar to web services (Service Oriented Architecture) , but WCF is flexible and its core serivices can be extended to suit our needs.so as industry standards grow, we can extend the WCF core.
WCF can operate with various things like MSMQ,Pipes, HTTP etc. This will be released with dot net framework 3.0 and orcas.
So without further delay we will develop a sample to enable us to understand better.
Create a new project of type “WCF service Library”
A class and a interface are created by default, delete them off. Also we have to add the following two “using statements” and references to “System.ServiceModel”
Using System.ServiceModel
Using System.Runtime.Serialization
Now we will start coding our custom interface and then implement taht interface.
[ServiceContract]
public interface IMathLIB
{
[OperationContract]
int Add(int val1,int val2);
}
Here, the ServiceContract attribuite specifies that the interface is the contract for the service. Not getting it? Ok ,WCF works on 3 basic principles : ABC, address,binding ,contract. If you know COM, you will know that we have an interface to specify the service provided. And then we use QueryInterface on the Factory class to get that interface (type casted object). This is nothing but contract. So IMathLIB is the service contract which we will be exposing (C of WCF). Now the other Attribute is “OperationContract”- this signifies that the operation is being exposed by the service.now we have to implement this interface :
public class MathService : IMathLIB
{
public int Addint(int val1,int val2)
{
return val1+val2;
}
}
Now we have a MathService class which implements IMathLIB.build this , a DLL is generated..lets name it as MathService.
Now is this enuf? No not at all..all we have doen is just created a service. Now we have to host that service in some other application and run that host application. This forms the server part of WCF. Then we have t ocraete a client to consume this service.
Creating the server is simple :
Create a simple cnsole application projecct and name it as MathServiceHost, add a refrence to “System.ServiceModel”, “System.IdentityModel”, and “System.Runtime.Serialization”. now add a reference to “MathService.dll”.
Now we will start coding for the host
internal class MathServiceHost
{
internal static ServiceHost myServiceHost = null;
internal static void StartService()
{
//Consider putting the baseAddress in the configuration system
//and getting it here with AppSettings
Uri baseAddress = new Uri("http://localhost:8000/MathService");
//Instantiate new ServiceHost
myServiceHost = new ServiceHost(typeof(MathService), new Uri( "http://localhost:8000/MathService"));
//Open myServiceHost
myServiceHost.Open();
}
internal static void StopService()
{
//Call StopService from your shutdown logic (i.e. dispose method)
if (myServiceHost.State != CommunicationState.Closed)
myServiceHost.Close();
}
}
Now add config file :
address="http://localhost:8000/MathService"
contract="MathServiceLIB.IMathLIB"
binding="basicHttpBinding"/>
Look at the address, binding and contract in the config file.it completes the jigsaw puzzle,does i t not?
Build this and it builds without any errors. So this is fine.
Now to develop a client :
Just create a simple console application named “MathClient” and then add a “service refrence “ this the URL specified in the address in the config file (shown above) and then we can use the service just like we use web services. bingo-- that does it.
But what if we want to add a new class in the service ? can we have operations on that class?
Well, we can!!!!
How? I will tell you .
Change your IMathLIB as shown below
[ServiceContract]
public interface IMathLIB
{
[OperationContract]
int Addint(int val1,int val2);
[OperationContract]
DataContract1 Add(DataContract1 dataContractValue,DataContract1 dataContractValue2);
}
And then ad the new class type which you want
[DataContract]
public class DataContract1
{
string firstName;
string lastName;
[DataMember]
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
[DataMember]
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public DataContract1 Add(DataContract1 data)
{
DataContract1 dc = new DataContract1();
dc.FirstName = this.firstName + data.FirstName;
dc.LastName = this.LastName + data.LastName;
return dc;
}
}
The attribute DataContract specifies that it is a datatype and the atribute “Datamember” specifies that it is a field.
Now w can code for our MathService class and implement the IMathLIB interface.
The rest is all as we did before
Hope this helps u.
Happy Coding !!!
Regards,
nandan
I will discuss about what WCF is a little later on. But now we will have to summarise how two different Applications can interact with each other. We have remoting which allows two different applications in different application domains to interact with each other. We have MSMQ using which two different applications can pass messages between them. We have WebServices using which we can make two applications interact.but all these have some shortcomings. For exampleMSMQ will be able to run on only windows machines.two applications have to conform to some specific standards if they have to use web services. Remoting will be possible only if both the applications are written in dot net.so to over come all these shortcomings, microsoft has come up with a new set of APIs to enable communication. This is Windows Communication Framework.
This is similar to web services (Service Oriented Architecture) , but WCF is flexible and its core serivices can be extended to suit our needs.so as industry standards grow, we can extend the WCF core.
WCF can operate with various things like MSMQ,Pipes, HTTP etc. This will be released with dot net framework 3.0 and orcas.
So without further delay we will develop a sample to enable us to understand better.
Create a new project of type “WCF service Library”
A class and a interface are created by default, delete them off. Also we have to add the following two “using statements” and references to “System.ServiceModel”
Using System.ServiceModel
Using System.Runtime.Serialization
Now we will start coding our custom interface and then implement taht interface.
[ServiceContract]
public interface IMathLIB
{
[OperationContract]
int Add(int val1,int val2);
}
Here, the ServiceContract attribuite specifies that the interface is the contract for the service. Not getting it? Ok ,WCF works on 3 basic principles : ABC, address,binding ,contract. If you know COM, you will know that we have an interface to specify the service provided. And then we use QueryInterface on the Factory class to get that interface (type casted object). This is nothing but contract. So IMathLIB is the service contract which we will be exposing (C of WCF). Now the other Attribute is “OperationContract”- this signifies that the operation is being exposed by the service.now we have to implement this interface :
public class MathService : IMathLIB
{
public int Addint(int val1,int val2)
{
return val1+val2;
}
}
Now we have a MathService class which implements IMathLIB.build this , a DLL is generated..lets name it as MathService.
Now is this enuf? No not at all..all we have doen is just created a service. Now we have to host that service in some other application and run that host application. This forms the server part of WCF. Then we have t ocraete a client to consume this service.
Creating the server is simple :
Create a simple cnsole application projecct and name it as MathServiceHost, add a refrence to “System.ServiceModel”, “System.IdentityModel”, and “System.Runtime.Serialization”. now add a reference to “MathService.dll”.
Now we will start coding for the host
internal class MathServiceHost
{
internal static ServiceHost myServiceHost = null;
internal static void StartService()
{
//Consider putting the baseAddress in the configuration system
//and getting it here with AppSettings
Uri baseAddress = new Uri("http://localhost:8000/MathService");
//Instantiate new ServiceHost
myServiceHost = new ServiceHost(typeof(MathService), new Uri( "http://localhost:8000/MathService"));
//Open myServiceHost
myServiceHost.Open();
}
internal static void StopService()
{
//Call StopService from your shutdown logic (i.e. dispose method)
if (myServiceHost.State != CommunicationState.Closed)
myServiceHost.Close();
}
}
Now add config file :
contract="MathServiceLIB.IMathLIB"
binding="basicHttpBinding"/>
Look at the address, binding and contract in the config file.it completes the jigsaw puzzle,does i t not?
Build this and it builds without any errors. So this is fine.
Now to develop a client :
Just create a simple console application named “MathClient” and then add a “service refrence “ this the URL specified in the address in the config file (shown above) and then we can use the service just like we use web services. bingo-- that does it.
But what if we want to add a new class in the service ? can we have operations on that class?
Well, we can!!!!
How? I will tell you .
Change your IMathLIB as shown below
[ServiceContract]
public interface IMathLIB
{
[OperationContract]
int Addint(int val1,int val2);
[OperationContract]
DataContract1 Add(DataContract1 dataContractValue,DataContract1 dataContractValue2);
}
And then ad the new class type which you want
[DataContract]
public class DataContract1
{
string firstName;
string lastName;
[DataMember]
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
[DataMember]
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public DataContract1 Add(DataContract1 data)
{
DataContract1 dc = new DataContract1();
dc.FirstName = this.firstName + data.FirstName;
dc.LastName = this.LastName + data.LastName;
return dc;
}
}
The attribute DataContract specifies that it is a datatype and the atribute “Datamember” specifies that it is a field.
Now w can code for our MathService class and implement the IMathLIB interface.
The rest is all as we did before
Hope this helps u.
Happy Coding !!!
Regards,
nandan
Sunday, November 18, 2007
Command Pattern
hi,
we will discuss about command pattern today !!!
scenario :
i am developing a game where i have my main character running,sitting and standing.
for now , will print "sit" when he sits,"stand" when he stands,"run" when he runs.
how do we go about this?
simple solution which falshes on to our mind right now is
1)develop and enum haveing its members as run,sit and stand.
2) in the user class,have this enum.
3) when any command is performed on the user handle it in a function called ExecuteCommand. In this function have an if loop and check for the enum.
voila, we get the output !!!!
so where is the problem?
well, my character is still evolving in the game. so now i identify a new scenario where the character has to sleep.so, i have to modify the user class by adding a new new enum "sleep" and then modify the if condition.....dont you think this is bad????
tomorrow i can identify some new user actions, then again i have to modify this?
naaah..this will not do...
how can we do a proper design for this?
this is where we use the command pattern.
in this pattern we make each and every user action as a class.and this class will handle its own command and perform the action necessary.
i mean " encapsulate a command into an object".
see the example below
public interface ICommand
{
void Execute();
}
public class RunCommand : ICommand
{
#region ICommand Members
public void Execute()
{
Console.WriteLine("Run Command executed");
}
#endregion
}
public class StandCommand : ICommand
{
#region ICommand Members
public void Execute()
{
Console.WriteLine("Stand Command executed");
}
#endregion
}
public class User
{
public void Action(ICommand cmd)
{
cmd.Execute();
}
}
and when i call this:
User Character = new User();
ICommand cmd = new RunCommand();
Character.Action(cmd);
so i create an instance of the command needed and pass it on to the Action function.
and then the class (command class) performs the necessary action.
now of i want to add a new command - sleep?
all i need to do is create a new class called Sleep,implement ICommand.
then implement the function Execute.
a new action has been introduced.
not if i want the user ot perfrom this :
ICommand SleepCmd = new SleepCommand();
Character.Action(SleepCmd);
this will perform the necessary action.
HAPPY CODING!!!!
regards,
nandan
we will discuss about command pattern today !!!
scenario :
i am developing a game where i have my main character running,sitting and standing.
for now , will print "sit" when he sits,"stand" when he stands,"run" when he runs.
how do we go about this?
simple solution which falshes on to our mind right now is
1)develop and enum haveing its members as run,sit and stand.
2) in the user class,have this enum.
3) when any command is performed on the user handle it in a function called ExecuteCommand. In this function have an if loop and check for the enum.
voila, we get the output !!!!
so where is the problem?
well, my character is still evolving in the game. so now i identify a new scenario where the character has to sleep.so, i have to modify the user class by adding a new new enum "sleep" and then modify the if condition.....dont you think this is bad????
tomorrow i can identify some new user actions, then again i have to modify this?
naaah..this will not do...
how can we do a proper design for this?
this is where we use the command pattern.
in this pattern we make each and every user action as a class.and this class will handle its own command and perform the action necessary.
i mean " encapsulate a command into an object".
see the example below
public interface ICommand
{
void Execute();
}
public class RunCommand : ICommand
{
#region ICommand Members
public void Execute()
{
Console.WriteLine("Run Command executed");
}
#endregion
}
public class StandCommand : ICommand
{
#region ICommand Members
public void Execute()
{
Console.WriteLine("Stand Command executed");
}
#endregion
}
public class User
{
public void Action(ICommand cmd)
{
cmd.Execute();
}
}
and when i call this:
User Character = new User();
ICommand cmd = new RunCommand();
Character.Action(cmd);
so i create an instance of the command needed and pass it on to the Action function.
and then the class (command class) performs the necessary action.
now of i want to add a new command - sleep?
all i need to do is create a new class called Sleep,implement ICommand.
then implement the function Execute.
a new action has been introduced.
not if i want the user ot perfrom this :
ICommand SleepCmd = new SleepCommand();
Character.Action(SleepCmd);
this will perform the necessary action.
HAPPY CODING!!!!
regards,
nandan
Thursday, November 15, 2007
FacadePattern - a centralised controller
hi,
been a long time since my last post eh?
sorry for that.
we shall discuss about a new design patter ntoday - Facade pattern
what exactly is a facade pattern?
technically speaking, it is a class which controls many other classes.something like a manager class.
let us take up a simple scenario :
i want to watch a movie at home..what all do i do?
1) i turn on the TV.
2) i turn on the speakers.
3) i turn on the DVD player
4) i turn off the lights
ok..so i have a class called user (that is me) which has to create instances of TV,DVD,Speakers,Lights and then on each of them call the start method. to switch off also its exactly same- we call the stop method. this is fine..no issues with this manner. but think of the user class, it has to maintain object references to the 4 classes. the user class may be very huge in itself. so we are increasing the burden on the user class. now if i have to have another class which has to perform the same 4 steps, tehn i have to have instances of these 4 classes again. and any new step included will change all the classes which perform these 4 steps.
so how can we make this more easier to manage? we will introduce a manager class in between..in this case "Remote" class.this will handle all the other 4 classes and perform the necessary steps.This is teh facade class.
advantages of using facade pattern are
1) the class (user class) which had to perform all the steps is not overloaded.
2) all the steps are maintained in a central location (Remote class).
look at the code sample below :
public interface IFacadeObject
{
void Start();
void Stop();
}
public class Remote : IFacadeObject
{
IFacadeObject DVDobj,SpeakerObj,LightObj,TVObj;
public Remote()
{
DVDobj = new DVD();
SpeakerObj = new Speakers();
LightObj = new Lights();
TVObj = new TV();
}
#region IFacadeObject Members
public void Start()
{
Console.WriteLine("Remote switched on");
TVObj.Start();
DVDobj.Start();
LightObj.Start();
SpeakerObj.Start();
}
public void Stop()
{
Console.WriteLine("Remote switched off");
TVObj.Stop();
DVDobj.Stop();
LightObj.Stop();
SpeakerObj.Stop();
}
#endregion
}
public class TV : IFacadeObject
{
public TV()
{
}
public void Start()
{
Console.WriteLine("TV switched on");
}
public void Stop()
{
Console.WriteLine("TV switched off");
}
}
public class AirCondition : IFacadeObject
{
public AirCondition()
{
}
public void Start()
{
Console.WriteLine("AirCondition switched on");
}
public void Stop()
{
Console.WriteLine("AirCondition switched off");
}
}
public class Speakers : IFacadeObject
{
public Speakers()
{
}
public void Start()
{
Console.WriteLine("Speakers switched on");
}
public void Stop()
{
Console.WriteLine("Speakers switched off");
}
}
public class DVD : IFacadeObject
{
public DVD()
{
}
public void Start()
{
Console.WriteLine("DVD switched on");
}
public void Stop()
{
Console.WriteLine("DVD switched off");
}
}
public class Lights : IFacadeObject
{
public Lights()
{
}
public void Start()
{
Console.WriteLine("Lights switched off");
}
public void Stop()
{
Console.WriteLine("Lights switched on");
}
}
This is our classes.
so when we call the "Remote" class instance, it will be doing all the necessary steps.
the call is made from the user class in this manner :
IFacadeObject RemoteObj = new Remote();
RemoteObj.Start();
Console.WriteLine("Things are working now ");
RemoteObj.Stop();
the output for this is
Remote switched on
TV switched on
DVD switched on
Lights switched off
Speakers switched on
Things are working now
Remote switched off
TV switched off
DVD switched off
Lights switched on
Speakers switched off
happy coding !!!!
regards,
nandan
been a long time since my last post eh?
sorry for that.
we shall discuss about a new design patter ntoday - Facade pattern
what exactly is a facade pattern?
technically speaking, it is a class which controls many other classes.something like a manager class.
let us take up a simple scenario :
i want to watch a movie at home..what all do i do?
1) i turn on the TV.
2) i turn on the speakers.
3) i turn on the DVD player
4) i turn off the lights
ok..so i have a class called user (that is me) which has to create instances of TV,DVD,Speakers,Lights and then on each of them call the start method. to switch off also its exactly same- we call the stop method. this is fine..no issues with this manner. but think of the user class, it has to maintain object references to the 4 classes. the user class may be very huge in itself. so we are increasing the burden on the user class. now if i have to have another class which has to perform the same 4 steps, tehn i have to have instances of these 4 classes again. and any new step included will change all the classes which perform these 4 steps.
so how can we make this more easier to manage? we will introduce a manager class in between..in this case "Remote" class.this will handle all the other 4 classes and perform the necessary steps.This is teh facade class.
advantages of using facade pattern are
1) the class (user class) which had to perform all the steps is not overloaded.
2) all the steps are maintained in a central location (Remote class).
look at the code sample below :
public interface IFacadeObject
{
void Start();
void Stop();
}
public class Remote : IFacadeObject
{
IFacadeObject DVDobj,SpeakerObj,LightObj,TVObj;
public Remote()
{
DVDobj = new DVD();
SpeakerObj = new Speakers();
LightObj = new Lights();
TVObj = new TV();
}
#region IFacadeObject Members
public void Start()
{
Console.WriteLine("Remote switched on");
TVObj.Start();
DVDobj.Start();
LightObj.Start();
SpeakerObj.Start();
}
public void Stop()
{
Console.WriteLine("Remote switched off");
TVObj.Stop();
DVDobj.Stop();
LightObj.Stop();
SpeakerObj.Stop();
}
#endregion
}
public class TV : IFacadeObject
{
public TV()
{
}
public void Start()
{
Console.WriteLine("TV switched on");
}
public void Stop()
{
Console.WriteLine("TV switched off");
}
}
public class AirCondition : IFacadeObject
{
public AirCondition()
{
}
public void Start()
{
Console.WriteLine("AirCondition switched on");
}
public void Stop()
{
Console.WriteLine("AirCondition switched off");
}
}
public class Speakers : IFacadeObject
{
public Speakers()
{
}
public void Start()
{
Console.WriteLine("Speakers switched on");
}
public void Stop()
{
Console.WriteLine("Speakers switched off");
}
}
public class DVD : IFacadeObject
{
public DVD()
{
}
public void Start()
{
Console.WriteLine("DVD switched on");
}
public void Stop()
{
Console.WriteLine("DVD switched off");
}
}
public class Lights : IFacadeObject
{
public Lights()
{
}
public void Start()
{
Console.WriteLine("Lights switched off");
}
public void Stop()
{
Console.WriteLine("Lights switched on");
}
}
This is our classes.
so when we call the "Remote" class instance, it will be doing all the necessary steps.
the call is made from the user class in this manner :
IFacadeObject RemoteObj = new Remote();
RemoteObj.Start();
Console.WriteLine("Things are working now ");
RemoteObj.Stop();
the output for this is
Remote switched on
TV switched on
DVD switched on
Lights switched off
Speakers switched on
Things are working now
Remote switched off
TV switched off
DVD switched off
Lights switched on
Speakers switched off
happy coding !!!!
regards,
nandan
Thursday, October 11, 2007
how to use NUnit for Test Driven Development(TDD)
hi,
i had spoken about TDD in one of my earlier posts.
now we can discuss about using some unit testing tools for TDD.One of the most common tools used is NUnit. the class which i want to test is a class which performs some basic math operations like add,subtract,divide and multiply.
the code for the class is as shown below
using System;
using System.Collections.Generic;
using System.Text;
namespace BasicMaths
{
public class Math
{
public Math()
{
}
public int Add(int i, int j)
{
return i + j;
}
public int Subtract(int i, int j)
{
return i - j;
}
public int Multiply(int i, int j)
{
return i * j;
}
public int Divide(int i, int j)
{
if(!CheckZero(j))
return i / j;
return 0;
}
public bool CheckZero(int i)
{
return( (i==0)? true:false);
}
}
}
now we have to give this class to some other component for consumption. But before that we have to make sure that each and every operation in this class works fine. For that we either have to write test stubs using NUnit. when we write a test class using NUnit we have to add NUnit.Framework.dll as a reference.Then we have to write the Test class.
As shown in the code below, the Class has to have an Attribute called [TestFixture], this is to convey to the compiler that the class is used for testing purpose. and each method which is used for testing should have the attribute [Test] to convey that the method is actually a NUnit test method.

we will build this project. a DLL will get created as a result. go to the folder where NUnit is installed. Run the file NUnit-GUI.exe. in this application, go to file->load rojet and then select the basicMathsTester.dll.

The DLL is loaded and all the classes along with their member functions are listed.

select on any function and click on the button run. If the method passes, then there will be aprogress bar in green color, else in case of failure the progress bar will be red in colour.

i had spoken about TDD in one of my earlier posts.
now we can discuss about using some unit testing tools for TDD.One of the most common tools used is NUnit. the class which i want to test is a class which performs some basic math operations like add,subtract,divide and multiply.
the code for the class is as shown below
using System;
using System.Collections.Generic;
using System.Text;
namespace BasicMaths
{
public class Math
{
public Math()
{
}
public int Add(int i, int j)
{
return i + j;
}
public int Subtract(int i, int j)
{
return i - j;
}
public int Multiply(int i, int j)
{
return i * j;
}
public int Divide(int i, int j)
{
if(!CheckZero(j))
return i / j;
return 0;
}
public bool CheckZero(int i)
{
return( (i==0)? true:false);
}
}
}
now we have to give this class to some other component for consumption. But before that we have to make sure that each and every operation in this class works fine. For that we either have to write test stubs using NUnit. when we write a test class using NUnit we have to add NUnit.Framework.dll as a reference.Then we have to write the Test class.
As shown in the code below, the Class has to have an Attribute called [TestFixture], this is to convey to the compiler that the class is used for testing purpose. and each method which is used for testing should have the attribute [Test] to convey that the method is actually a NUnit test method.
we will build this project. a DLL will get created as a result. go to the folder where NUnit is installed. Run the file NUnit-GUI.exe. in this application, go to file->load rojet and then select the basicMathsTester.dll.
The DLL is loaded and all the classes along with their member functions are listed.
select on any function and click on the button run. If the method passes, then there will be aprogress bar in green color, else in case of failure the progress bar will be red in colour.
Monday, September 3, 2007
Bridge Pattern
hi,
Another new post today :)
scenario :
I have a car factory which manufactures cars.
I have few models of cars which use petrol as fuel. So the design for this will be an interface ICar which is implemented by cars. So the names of these car classes are : ToyotaPetrol, SuzukiPetrol etc. until now i have a flexible manufacturing unit i can introduce new cars any time i want. but now market changes, my competitors also do the same. So i think of introducing new cars which run on diesel as well. so how do i go about this? add new classes : ToyotaDiesel, SuzukiDiesel. is this right? no..not at all...reason being : to introduce any new car, i will have to add two classes : one for petrol and one for diesel. can this be eliminated? yes.
how?
separate the Fuel and the car and then have some method to change the fuelling mechanism for the car object. this is know as Bridge pattern
bridge pattern says : separate the abstraction from it implementation.
look at the code below :
public abstract class ICar
{
protected IFuel _Fuel;
public void SetFuel(IFuel Fuel)
{
_Fuel = Fuel;
}
public abstract void Print();
}
public class Toyota: ICar
{
public override void Print()
{
Console.Write("Toyota with ");
_Fuel.Print();
}
}
public class Suzuki: ICar
{
public override void Print()
{
Console.Write("Suzuki with ");
_Fuel.Print();
}
}
public interface IFuel
{
void Print();
}
public class Petrol : IFuel
{
public void Print()
{
Console.WriteLine("Petrol");
}
}
public class Diesel : IFuel
{
public void Print()
{
Console.WriteLine("Diesel");
}
}
method of invoking :
ICar objcar = new Toyota();
IFuel objFuel = new Petrol();
objcar.SetFuel(objFuel);
objcar.Print();
so the fuel and car are very much separate now.
i can change the fuelling machanism by calling the setFuel() method.
When i initially got to know about this pattern, i mistook this to be like the decorator pattern. actually both are different. Bridge separates the abstraction and implementation (as seen with the car and fuel) but decorator wraps an object inside another object in turn adding more functionality to the object.
happy coding !!!
Another new post today :)
scenario :
I have a car factory which manufactures cars.
I have few models of cars which use petrol as fuel. So the design for this will be an interface ICar which is implemented by cars. So the names of these car classes are : ToyotaPetrol, SuzukiPetrol etc. until now i have a flexible manufacturing unit i can introduce new cars any time i want. but now market changes, my competitors also do the same. So i think of introducing new cars which run on diesel as well. so how do i go about this? add new classes : ToyotaDiesel, SuzukiDiesel. is this right? no..not at all...reason being : to introduce any new car, i will have to add two classes : one for petrol and one for diesel. can this be eliminated? yes.
how?
separate the Fuel and the car and then have some method to change the fuelling mechanism for the car object. this is know as Bridge pattern
bridge pattern says : separate the abstraction from it implementation.
look at the code below :
public abstract class ICar
{
protected IFuel _Fuel;
public void SetFuel(IFuel Fuel)
{
_Fuel = Fuel;
}
public abstract void Print();
}
public class Toyota: ICar
{
public override void Print()
{
Console.Write("Toyota with ");
_Fuel.Print();
}
}
public class Suzuki: ICar
{
public override void Print()
{
Console.Write("Suzuki with ");
_Fuel.Print();
}
}
public interface IFuel
{
void Print();
}
public class Petrol : IFuel
{
public void Print()
{
Console.WriteLine("Petrol");
}
}
public class Diesel : IFuel
{
public void Print()
{
Console.WriteLine("Diesel");
}
}
method of invoking :
ICar objcar = new Toyota();
IFuel objFuel = new Petrol();
objcar.SetFuel(objFuel);
objcar.Print();
so the fuel and car are very much separate now.
i can change the fuelling machanism by calling the setFuel() method.
When i initially got to know about this pattern, i mistook this to be like the decorator pattern. actually both are different. Bridge separates the abstraction and implementation (as seen with the car and fuel) but decorator wraps an object inside another object in turn adding more functionality to the object.
happy coding !!!
Friday, August 24, 2007
Template Method : template for execution
Hi,
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 !!!
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 !!!
Subscribe to:
Posts (Atom)