Saturday, 16 December 2006

Try Get Design pattern

This is quite an important design pattern which I haven’t seen used much (I found it in Brad Abrams brilliant book)

Basically when you are trying to get something from a list there are three ways this can be done:

A) [VERY BAD – never use this method unless you have checked the id is in the dictionary/hashtable]

Try
{
Object oOurValue = m_oDictionary[iID];
}
Catch(Exception err)
{
//HandleValueNotFound
}

B) [Not a bad way of doing it]

Object oOurValue = null;
If(m_oDictionary.HasValue(iID))
{
oOurValue = m_oDictionary [iID];
}
Else
{
//HandleValueNotFound
}

C) [The best way]

Object oOurValue = null
If(!m_oDictionary.TryGetValue(iID, out oOurValue))
{
//HandleValueNotFound
}


TryGetValue return true or false depending on the operations success, and places the result into the parameter passed in – if you implement a Get method which could fail (e.g. throw an exception), then at least consider implementing a tryget method

This could be used in loads of places – TrySave, TryOpen etc.

All value types implement this method for parsing - so for example to convert a string to an int you should use the following:-

String strANum = “001”;
String strBNum = “Not a num!”;

Currently you would have to do:
Try
{
Int iANum = Int.parse(strANum);
Int iBNum = Int.parse(strBNum);

}
Catch(Exception err)
{
//Handle not a num
}

Should be done as:

Int iANum =-1;
Int iBNum =-1;

If(!int.TryParse(strANum, out iANum) !int.TryParse(strBNum, out iBNum))
{
//Handle not a num
}

Much better:) (all Parse methods should provide a tryparse method also)

Ross

1 comment:

Gabriela said...

Hello, good post, i'm from argentina, i recently started to develop with VS 2005 and i'm still learning about it.