Today I was working on method called “GetSettingValue” that has multiple overloads to satisfy different data types.
Initially I created 3 overloads – String, Integer and Boolean. But then I realized what about others for example Date and Long? I first looked to create more overloads for each value type data type. I soon realized its lot of code to write and maintain. See following code for example, it reads setting for Integer filed and return it (or default in case of failure).
Public Function GetSettingValue(ByVal SettingName As String, ByVal DefaultValue As Integer) As Integer
If Settings(SettingName) Is Nothing Then Return DefaultValue
Try
Return CType(Settings(SettingName), Integer)
Catch
Return DefaultValue
End Try
End Function
This is 7 line of code for only one data type and I have to do same for 8 other data types. That is too much code for no meaning. What if in future I have to change only one line in each method? That single line change work becomes total 9 lines of work (and test). So having that many overloads was not making sense to me. Then I realized this is perfect case for using .NET Generics. See following code
Public Function GetSettingValue(Of T)(ByVal SettingName As String, ByVal DefaultValue As T) As T
If Settings(SettingName) Is Nothing Then Return DefaultValue
Try
Return CType(Settings(SettingName), T)
Catch
Return DefaultValue
End Try
End Function
As you can see I have code that satisfies all requirements from past 63 lines in just bare 7 lines. Also now any change/optimization required has to be done in single methods only.
To learn more about Generics see
http://msdn2.microsoft.com/hi-in/magazine/cc164094(en-us).aspx
http://www.developer.com/net/vb/article.php/3521486
http://msdn2.microsoft.com/en-us/library/aa479866.aspx