Wednesday, October 20, 2004
« One way SOA is fundamentally new and dif... | Main | Technologies for crossing tiers vs cross... »

Jason Bock has been trying strange stuff with generics.

 

I have as well, with the intent of addressing some uses for CSLA .NET 2.0. Here’s one important concept I’ve figured out:

 

Public Class BaseClass

  Public Function BaseAnswer() As Integer

    Return 42

  End Function

End Class

 

Public Class AddMethod(Of T As {New, AddMethod(Of T)})

  Inherits BaseClass

 

  Public Shared Function GetObject() As T

    Return New T

  End Function

End Class

 

Public Class StrangeMethod

  Inherits AddMethod(Of StrangeMethod)

 

  Public Function GetStrangeAnswer() As Integer

    Return 123321

  End Function

End Class

 

Public Class TestAddMethod

  Public Sub Test()

    Dim extendedBaseClass As StrangeMethod = StrangeMethod.GetObject

    extendedBaseClass.BaseAnswer()

    extendedBaseClass.GetStrangeAnswer()

  End Sub

End Class

 

The primary benefits are:

 

1)      The consumer (the Test method) doesn’t have to deal with generic syntax at all – yea!

2)      The code inside the generic can be minimized – very little code needs to be in the AddMethod class. This is good, because debugging inside generics is limited compared to inside regular classes. Most code can be put into BaseClass rather than AddMethod, and AddMethod can include only code requiring the use of generics (unlike my trivial example here).

3)      By keeping as much code as possible in BaseClass we gain better polymorphism. Generics aren’t polymorphic, so the fewer public methods in a generic the better. Putting public methods into a base class or interface is far preferable in most cases.

4)      Note that AddMethod is constrained to only be used through inheritance. I thought this was a neat trick that helps enforce this particular model for using generics. AddMethod is only useful for creation of a subclass.