I created a custom collection class with some methods: each of these has some parameters and throws an exception if a parameter is not valid.
For example, the Add and Remove methods throw an NullReferenceException if one of their parameters is null.
The Replace method replaces an item in the collection with another specified object: to reach the goal, it first calls the Remove method and after the Add method. Obviously the Replace method could throw exceptions if at least one of the specified parameters is null, because Remove and Add methods could throw exceptions.
Is this the right way to go? Or should I also check the parameters in the Replace method as in the following code?
In fact, in this second case, each check would be executed twice: first in the Replace method and after in the Remove and Add methods, which are called by Replace, and in other cases the checks may be rather expensive.
Thanks a lot for any advice!
For example, the Add and Remove methods throw an NullReferenceException if one of their parameters is null.
VB.NET:
Sub Add(ByRef word As String)
If (word Is Nothing) Then
Throw New NullReferenceException("word must be not null")
End If
...
End Sub
Sub Remove(ByRef word As String)
If (word Is Nothing) Then
Throw New NullReferenceException("word must be not null")
End If
...
End Sub
Sub Replace(ByRef word1 As String, ByRef word2 As String)
Remove(word1)
Add(word2)
End Sub
The Replace method replaces an item in the collection with another specified object: to reach the goal, it first calls the Remove method and after the Add method. Obviously the Replace method could throw exceptions if at least one of the specified parameters is null, because Remove and Add methods could throw exceptions.
Is this the right way to go? Or should I also check the parameters in the Replace method as in the following code?
VB.NET:
Sub Replace(ByRef word1 As String, ByRef word2 As String)
If (word1 Is Nothing) Then
Throw New NullReferenceException("word1 must be not null")
End If
If (word2 Is Nothing) Then
Throw New NullReferenceException("word2 must be not null")
End If
Remove(word1)
Add(word2)
End Sub
Thanks a lot for any advice!
Last edited: