rbulph Posted February 15, 2008 Posted February 15, 2008 Working on the basis that all repetition is bad, is there a good way to write code to call constructors for a range of class types all deriving from a common base? e.g. Dim h As base If x = 0 Then h = New base(1, "ABC") ElseIf x < 0 Then h = New inheritor1(1, "ABC") ElseIf x > 0 Then h = New inheritor2(1, "ABC") End If Public Class base Public Sub New(ByVal x As Long, ByVal y As String) End Sub End Class Public Class inheritor1 Inherits base Public Sub New(ByVal x As Long, ByVal y As String) MyBase.New(x, y) End Sub End Class Public Class inheritor2 Inherits base Public Sub New(ByVal x As Long, ByVal y As String) MyBase.New(x, y) End Sub End Class I know you can use Activator.CreateInstance but then there's no check on whether the array that you're sending to the constructor is valid until runtime. So any thoughts? Quote
Leaders snarfblam Posted February 15, 2008 Leaders Posted February 15, 2008 I think something along the lines of the following would be your best bet. Dim h As base = base.Create(1, "ABC", x) Public Class base Public Sub New(ByVal x As Long, ByVal y As String) End Sub Public Shared Function Create(Byval x As Long, ByVal y As String, ByVal z As Long) If x < 0 Then Return New inheritor1(x, y) If x > 0 Then Return New inheritor2(x, y) Return New base(x, y) End Class Public Class inheritor1 Inherits base Public Sub New(ByVal x As Long, ByVal y As String) MyBase.New(x, y) End Sub End Class Public Class inheritor2 Inherits base Public Sub New(ByVal x As Long, ByVal y As String) MyBase.New(x, y) End Sub End Class If you are only going to do this once then I hardly see a problem with the if-elseif chain you used in your example. Otherwise, a shared method like this or a factory pattern may be best. The fact is that your constructors are really just different constructors that just happen to have the same parameters. Its like inheriting a class and shadowing a method with another that has an identical signature. They have no functional relationship. I don't know how else you could simplify the situation. I think ideally it would be nice if there were some way to inherit constructors and place restrictions on a deriving class' constructors to give them polymorphic behavior, but that could get messy fast, which is probably why most languages deal with constructors the way they do. On a side note, I hope you don't take that extreme principal to heart. At some point abstraction becomes counter-productive and repetition is unavoidable. Quote [sIGPIC]e[/sIGPIC]
rbulph Posted February 16, 2008 Author Posted February 16, 2008 Thanks. I'm only doing this once, with four class types, so the repetition isn't really a problem. It's just become a bit instinctive to try to cut out repetition where I see it... Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.