A Pitfall for Beginners when Working with a Dictionary
Posted by admin - Apr 23, 2008 Articles, Eyas Kopty, Meir Bar-Tal, Yasmin Helled 0 0 Views : 567 Receive Updates For This Category
Article Tools
- Print this page
- Add Comment
- Send to Friend
- Last Updated on :
Jul 15, 2011
Introduction
First and foremost I wish to thank two of my team members, Yasmin Helled and Eyas Kopty, who actually brought this issue to my attention. This post actually replaces an earlier post in which I prematurely and erroneously declared the issue as being a bug. My apologies to you, my loyal readers, for falling with such pitfall. I hope this short article will enable you avoid another one, even more substantial – one that can impact the way your code behaves.
Discussion
Yasmin had showed me a piece of code similar to the following (I simplified it a bit for illustration purposes):
If Not (objDic.Exists("MyKey") Or IsNumeric(objDic("MyKey"))) Then MsgBox "Key Not Found" Else MsgBox "Key Found: " & objDic("MyKey") End If
The key, needless to say, was not previously added, but the condition consistently entered the Else clause, printing an Empty value in the MsgBox. This sounded weird to Yasmin, who had forgotten that VBScript always checks ALL conditional clauses, so that even though the first part of the condition already returned true, the second part is also checked. This resulted in runtime problems, since the key thus added contained an empty value!
To overcome this problem, the above code was replaced with the following:
'Declare variables Dim objDic, strKey 'Create instance of Dictionary Set objDic = CreateObject("Scripting.Dictionary") 'Assign value to required key strKey = "MyKey" If Not (objDic.Exists(strKey)) Then 'Check if the key exists MsgBox "Key " & strKey & " was not found." ElseIf Not IsNumeric(objDic(strKey)) Then 'The key exists so check if it's numeric MsgBox "Value is not numeric: " & objDic(strKey) Else 'Report that the validation succeeded MsgBox "Key " & strKey & " was found and the value is " & objDic(strKey) End If
So that functional independence between key existence and value type validation is achieved.
Conclusion
When addressing a non-existing key in a Dictionary object, the add method is invoked by default. The problem is that the Windows Script Host does not inform during runtime that there is a missing key. Moreover, the automatically assigned Empty value may cause trouble to our subsequent code execution. I hope that bringing up this issue will benefit programmers and enable them to avoid such a pitfall.
*Note: This revised post replaces a previous post titled "Amazing Bug in the Dictionary Object!"


