DevDisasters
Collections Class
A Junior Developer Learns that Seniority Doesn't Mean Smarter.
Yakir was excited to take a new job. During his first week, a senior developer, James, approached Yakir for some help with .NET collections.
"I can never seem to remember," James said. "What collection type do I want to use: an ArrayList or Hashtable?"
In any other circumstance, Yakir would have considered this question an impromptu quiz from a higher-up. But in James' case, it was a legitimate query.
"It all depends on how you want to access your data," Yakir explained. "If you want to access your data by index, you store it in an ArrayList. If it's easier to store things as a key-value pair, then you use a Hashtable."
Hashing It Out
A few days later, however, James ran into some trouble. "I think you were wrong about the Hashtable," he said. "Once I have real data in there, it takes almost five seconds to add, remove or find an item."
Yakir knew something was wrong and sat with James to look at his code:
class HashTable
{
public object[] keys;
public object[] vals;
public HashTable()
{
keys = new object[0];
vals = new object[0];
}
public void Add(object key,
object val)
{
Array.Resize(ref keys,
keys.Length + 1);
Array.Resize(ref vals,
vals.Length + 1);
keys[keys.Length - 1] = key;
vals[vals.Length - 1] = val;
}
public void Remove(object key)
{
object[] tKeys = new object[0];
object[] tVals = new object[0];
for (int i = 0;
i <= keys.Length - 1; i++)
{
if (!keys[i].Equals(key))
{
Array.Resize(
ref tKeys,
tKeys.Length + 1);
Array.Resize(
ref tVals,
tVals.Length + 1);
tKeys[tKeys.Length - 1]
= keys[i];
tVals[tVals.Length - 1]
= vals[i];
}
}
keys = tKeys;
vals = tVals;
}
public object GetItem(object key)
{
for (int i = 0;
i <= keys.Length - 1; i++)
{
if (keys[i].Equals(key))
{
return vals[i];
}
}
return null;
}
public int NumberOfItems
{
get
{
return keys.Length;
}
}
}
Yakir was baffled. "Why didn't you use the built-in Hashtable class from System.Collections?" he asked.
"I checked it out," James explained, "but it had too many functions. In my experience, that means it'll be slow. My class only has 3 functions, so it's much more efficient."
After a few weeks on the job, Yakir learned a valuable lesson: One's title had little to do with one's coding skills.
About the Author
Alex Papadimoulis lives in Berea, Ohio. The principal member of Inedo, LLC, he uses his 10 years of IT experience to bring custom software solutions to small- and mid-sized businesses and to help other software development organizations utilize best practices in their products. On the Internet, Alex can usually be found answering questions in various newsgroups and posting some rather interesting real-life examples of how not to program on his Web site TheDailyWTF.com. You can contact Alex directly via email at [email protected].,