Custom collection design/style opinion requested

  • Thread starter Thread starter Chris Dunaway
  • Start date Start date
C

Chris Dunaway

VB.Net: I have create a custom collection to hold instances of my
custom class. The collection has an Item property which is set as the
default property.

I can use code such as this to retrieve an item by index or key:

Dim MyInst As MyCustomClass = MyColl("key")

My question is how should the situation of the key (or index) not
present in the list be handled?

Right now, if "key" was not in the collection, the collection would
throw an exception. To deal with that I would have to code like this:

Dim MyInst As MyCustomClass
Try
MyInst = MyColl("key")

'Process instance here

Catch ex As KeyNotFoundException
'Do something here like display a message, or whatever
End Try

But I am wondering if it would be better to not throw an exception but
to simply return Nothing if the key is not found. Then the code would
be like this:

Dim MyInst As MyCustomClass
MyInst = MyColl("key")
If MyInst Is Nothing Then
'Log error, display message, or whatever
Else
'Process instance here
End If

The cost of the exception in the first method would be high the first
time, but not afterwards, whereas the second method is more defensive.
Or would it be better to do something like this:

If MyColl.ContainsKey("key") Then
Dim MyInst As MyCustomClass = MyColl("key")
'Process instance here
Else
'Display message that key not found here
End If

What, if any, is the "standard" or best practice for such things?

Thanks for any opinions.

Chris
 
Exceptions incur significant overhead (especially with regards to your call
stack), so if your collection cannot contain null items, I'd say return
null, but if you do allow keying of null slots (i.e. myList["myKey"] =
null;), you will need to go the exception route to differentiate between the
two scenarios (ItemNotFound vs. ItemFoundButIsNull)
 
Back
Top