Too many identical simple methods using an interface - vb.net

I have a few dozen classes which all implement the same interface and many of the methods have identical implementation. I have to do a lot of copy and paste whenever I add a new class. How can I get less code duplication?
I've heard that you should put the common code in a helper class but a lot of these methods are really trivial so calling a helper method is barely any simpler than doing the actual work.
Inheritance would save re-declaring all these methods but it would make it messy for the few classes that don't have the identical implementation.
Examples:
Identical in nearly every class...
Public Sub ThingWasDeleted(ByVal deletedThing As Thing) Implements Iinterface.ThingWasDeleted
If MyThing Is deletedThing Then
MyThing = Nothing
End If
End Sub
...but occasionally different:
Public Sub ThingWasDeleted(ByVal deletedThing As Thing) Implements IInterface.ThingWasDeleted
'Do nothing
End Sub
Identical in every class but already just as simple as calling a common helper method:
Public ReadOnly Property DisplayName() As String Implements IInterface.DisplayName
Get
Return DisplayNameShared
End Get
End Property

If you put these methods in a helper class, wouldn't that make it just as messy (if not more) than having an abstract base class where you can override the base class's functionality when needed?
For example:
Public MustInherit Class BaseClass
Public ReadOnly Property DisplayName() As String
Get
Return DisplayNameShared
End Get
End Property
Public Overridable Sub ThingWasDeleted(ByVal deletedThing As Thing)
If MyThing Is deletedThing Then
MyThing = Nothing
End If
End Sub
End Class
This provide a definition of the property that all inheriting classes can use, and gives the inheriting class an option to override and create their own implementation of ThingWasDeleted.
For example:
Public Class MyClass
Inherits BaseClass
Public Overrides Sub ThingWasDeleted(ByVal deletedThing As Thing)
' Do nothing
End Sub
End Class
On the other hand, if you wrote a helper class, you'd have to define every method, and the developer (which may or may not be you) would have to know which method to change. Additionally, instead of having the option to use the existing functionality in the base (abstract) class, every class you create will have to call each of the proper helper methods.
Personally, I prefer the former option, mainly because the inheriting classes don't have to call anything to get the base functionality established in the base class, and can override what they need to on a case-by-case basis. Conversely, having them all in a helper class means you have to at least write the code to call each of the necessary helper methods in every class you have.

Related

Abstract class using an interface impleented in subclass?

I have an idea that uses both an abstract class and an interface, but i'm not sure if its possible to do what I am thinking of and how.
I have an abstract class modeling a device, containing only abstract functionality. When implemented this class basically serves as a driver for the specific device.
Each device may have different features, I am attempting to model the feature sets as different interfaces that may or may not be implemented by the class designer.
Is there a mechanism for me to determine if a subclass of the device class is implementing these interfaces. I have to determine it FROM the super class, then be able to call the functions defined in the subclass from there.
This sounds impossible to me, but I'm just curious if someone else has more intuition, or possibly a better solution.
In the example below I've illustrated my point. I would like to be able ot have an object of type device, and call the functions implemented in the subclass through some mechanism.
Thanks!
Public MustInherit Class Device
Public MustOverride Sub One()
Public Function SupportsBonding As Boolean
'Returns true if subclass implments interface
End Function
End Class
Public Interface Bonding
Sub Two()
Sub Three()
End Interface
Public Class Device1
Inherits Device
Implements Bonding
Public Sub Two()
End Sub
Public Sub Three()
End Sub
End Class
You can always use a TypeOf operator using the Me keyword, something like:
If TypeOf Me Is IAmSomeInterface Then
...
End If
Even if this code is running in the superclass, it will always work against the runtime type of the object, so you'll get the subclass information.
Or, if you're planning to call methods on the interface, you might use a TryCast instead:
Dim someObject = TryCast(Me,IAmSomeInterface)
If Not someObject Is Nothing Then
someObject.DoSomething()
End If

Implement an interface in partial class

I need all my TableAdapters to implement a custom interface. The problem is that some of the members defined by the interface reside in the DataSet's designer file, which I don't want to (and shouldn't) alter, as that code will be regenerated automatically. I can't relocate those members to my code file either for the same reason. What's my way out of it?
When you implement an interface, the members you declare do not have to have the same names as the members of the interface and they don't have to be public. Let's say that you have this designer-generated class:
Partial Public Class SomeClass
Public Sub FirstMethod()
Console.WriteLine("FirstMethod")
End Sub
Public Sub SecondMethod()
Console.WriteLine("SecondMethod")
End Sub
End Class
and you want it to implement this interface:
Public Interface ISomeInterface
Sub FirstMethod()
Sub ThirdMethod()
End Interface
Notice that the interface has a method named FirstMethod but SomeClass already has a method named FirstMethod. You can add your own partial class to implement the interface like this:
Partial Public Class SomeClass
Implements ISomeInterface
Private Sub FirstMethodInternal() Implements ISomeInterface.FirstMethod
Me.FirstMethod()
End Sub
Public Sub ThirdMethod() Implements ISomeInterface.ThirdMethod
Console.WriteLine("ThirdMethod")
End Sub
End Class
The method that implements ISomeInterface.FirstMethod is not named FirstMethod so it doesn't clash with the existing method with that name and it is also Private so it cannot be accessed from outside using a reference of type SomeClass. Using a reference of type ISomeInterface is another matter though. If you use code like this:
Dim sc As ISomeInterface = New SomeClass
sc.FirstMethod()
sc.ThirdMethod()
you'll find that the FirstMethodInternal method of your SomeClass object gets invoked and, in turn, invokes the FirstMethod method of the same object. Try running that code and placing breakpoints on the FirstMethod and FirstMethodInternal methods to prove it to yourself.

Error when passing friend class as type from public class to friend base class

Disclaimer: I am fairly new to working with generics so I am not entirely sure if what I am trying to do even makes sense or is possible.
I have a bunch of user controls in a project. All of these user controls share a similar property so I want to move it into a base class. The only difference is the return type of the property.
I have three classes interacting in this scenario. The first class is a base type, which inherits from CompositeControl and will be inherited by other classes in my project:
Friend Class MyBaseClass(Of T As {New})
Inherits CompositeControl
Private _someProperty As T = Nothing
Protected ReadOnly Property SomeProperty As T
Get
// dumbed down for the sake of example
If _someProperty Is Nothing Then
_someProperty = New T()
End If
Return _someProperty
End Get
End Property
End Class
Then I have this control class, which inherits from MyBaseClass:
Public Class MyControlClass
Inherits MyBaseClass(Of MyReturnTypeClass)
// snip...
End Class
And finally MyReturnTypeClass which is what the base's SomeProperty should return:
Friend Class MyReturnTypeClass
Public Property AutoProperty1 As Boolean = False
Public Property AutoProperty2 As String = String.Empty
// etc
End Class
When I attempt to build the project, I get this error from MyControlClass:
Inconsistent accessibility: type argument 'MyReturnTypeClass' is less accessible than Class 'MyControlClass'.
I need MyControlClass to be Public so it can be consumed by other projects, and I also want the MyBaseClass and MyReturnTypeClass to be Friend so they cannot be seen/used by consumers. Am I just missing some special keyword somewhere or is this not possible?
You cannot inherit from a base class that is less accessible than the derived class. So for instance, this won't work:
Friend Class MyBase
End Class
Public Class MyDerived
Inherits MyBase ' Won't compile because MyBase is less accessible
End Class
Therefore, since in your example, MyBaseClass(T) has is a friend type, but you are trying to inherit from it into a public MyControlClass type. Therefore, even if you took generics and MyReturnTypeClass out of the "equation", it still wouldn't work.
However, with generics, even if no member of the public interface of the class actually uses the generic type, the type must still be at least as accessible as the derived type. For instance:
Public Class MyBase(Of T)
' T not actually used at all
End Class
Friend Class MyOtherType
End Class
Public Class MyDerived
Inherits MyBase(MyOtherType) ' Won't compile because MyOtherType is less accessible
End Class
The base class must be at least as accessible as the derived class. This is a language restriction (see here).
If you intend to avoid MyBaseClass being instantiated by consumers, consider marking it Public MustInherit instead of Friend. Hope this helps.

Storing an object that implements multiple interfaces and derives from a certain base (.net)

In .net, it's possible to use generics so that a function can accept arguments which support one or more interfaces and derive from a base type, even if there does not exist any single type from which all valid argument types derive. For example, one could say:
Sub Foo(Of T As {IInterface1, IInterface2, SomeBaseType})(Param as T)
and be allowed to pass any derivative of SomeBaseType which implements both IInterface1 and IInterface2. This will work even if SomeBaseType does not support Interface1 and Interface2, and classes which do implement those interfaces don't share any common ancestor that also implements them.
This can be very convenient if one won't need to keep the parameter anywhere after the function has exited. Unfortunately, I can't figure out a way to persist the passed-in parameter in such a way that it can later be passed to a similar function, except perhaps by using Reflection. Is there any nice way of doing that?
The closest I've been able to come up with is to define an interface INest (perhaps not the best name--can anyone improve it?) thus:
Interface INest(Of Out T)
Function Nest() As T
End Interface
And for any interface that will be used in combination with others or with base-class "constraint", define a generic version as illustrated below
Interface IFun1
' Any members of the interface go here, e.g. ...'
Sub DoFun1()
End Interface
Interface IFun1(Of Out T)
' This one does nothing but inherit'
Inherits IFun1, INest(Of T)
End Interface
A class which will support multiple interfaces should declare itself as implementing the generic ones, with itself as the type argument.
Class test123a
Inherits sampleBase
Implements IFun1(Of test123a), IFun2(Of test123a), IFun3(Of test123a)
End Class
If that is done, one can define a function argument or class variable that supports multiple constraints thusly:
Dim SomeField as IFun1(Of IFun2(Of IFun3(Of sampleBase)))
and then assign to it any class derived from sampleBase, which implements those interfaces. SomeField will implement IFun1; SomeField.Nest will implement IFun2; SomeField.Nest.Nest will implement IFun3. Note that there's no requirement that IFun1, IFun2, IFun3, or sampleBase share any common derivation other than the generic interfaces inheriting from INest(Of T). Note also that, no matter how many INest-derived interfaces a class implements, it only needs to define one implementation of INest(Of T).Nest.
Not exactly beautiful, but there are two nice things about it: (1) any concrete class which in fact implements the necessary interfaces can be assigned directly to a field declared as above, without a typecast; (2) while fields which chain the types in a different order are not assignment compatible, they may be typecast to each other.
Is there any better way to store something in such a way that it's "known" to support multiple interfaces and derive from a certain base type? Given that one can write such code in a type-safe manner, it would seem like the .net 2.0 CLR could probably support such a thing quite nicely if compilers offered a little assistance. I'm unaware of any particularly nice approach with present compilers, though.
The best way I can think of is to make an abstract storage and generic implementation of this storage. For example (excuse my VB.NET):
MustInherit Class Storage
Public MustOverride Sub DoSomething()
End Class
Class Storage(Of T As {IInterface1, IInterface2, SomeBaseType})
Inherits Storage
Public Overrides Sub DoSomething()
' do something with Value.
End Sub
Public Value As T
End Class
And usage
Dim S As Storage
Sub Foo(Of T As {IInterface1, IInterface2, SomeBaseType})(ByVal Param As T)
S = New Storage(Of T) With {.Value = Param}
End Sub
Sub UseS()
S.DoSomething();
End Sub
Update: Ok, because we may not be able identify in advance all of the actions:
MustInherit Class Storage
MustOverride ReadOnly Property SomeBaseType As SomeBaseType
MustOverride ReadOnly Property IInterface1 As IInterface1
MustOverride ReadOnly Property IInterface2 As IInterface2
End Class
Class Storage(Of T As {IInterface1, IInterface2, SomeBaseType})
Inherits Storage
Public Value As T
Public Overrides ReadOnly Property IInterface1 As IInterface1
Get
Return Value
End Get
End Property
Public Overrides ReadOnly Property IInterface2 As IInterface2
Get
Return Value
End Get
End Property
Public Overrides ReadOnly Property SomeBaseType As SomeBaseType
Get
Return Value
End Get
End Property
End Class

Protected Constructors and MustInherit/ Abstract class

What is the difference between a class with protected constructors and a class marked as MustInherit? (I'm programming in VB.Net but it probably equally applies to c#).
The reason I ask is because I have an abstract class that I want to convert the constructors to shared/static methods. (To add some constraints).
I can't do this because it's not possible to create an instance in the shared function.
I'm thinking to just remove the MustInherit keyword. Will this make any difference?
Thanks.
ETA:
I think i've answered my question, If I remove the MustInherit keyword, I can no longer include the MustOverrides, which are very useful.
With that in mind, is there any way around my problem?
ETA2:
To clarify, I can't do the below unless I remove the MustInherit keyword?
Public MustInherit MyBaseClass
Private Sub New()
End Sub
Protected Function CreateInstance(ParmList) As MyBaseClass
If ParmList is Ok Then Return New MyBaseClass()
End Function
End Class
You can call the Protected constructor using reflection and instantiate the class but you can't instantiate an abstract class in this way. You can declare MustOverride methods in MustInherit classes but Protected constructor can enforce nothing on derived classes.
You should always declare classes that are conceptually abstract as MustInherit. Protected constructors can be useful when you are providing it along with some Public overloads to provide some more functionality to derived classes.
If the class only has a protected constructor, it is still possible to have an instance of the class which can stand on its own. It would require working around the protected constructor, such as using reflection.
If the class is marked as MustInherit, it is impossible to have an instance of that class on its own. Instances can only be created of the derived/inherited classes.
Not really sure what you want.
If you need to create an object of the abstract class, I recommend you create a private class implementation of your abstract class and return it in your CreateInstanceMethod:
Public MustInherit MyBaseClass
Private BaseClassImplementation
Inherits MyBaseClass
...
End Class
Public Function CreateInstance(paramList) as MyBaseClass
If paramList Is Ok Then Return New BaseClassImplementation
End Function
End Class
However, if you want to add some constraints to the construction, I recommend to throw exceptions:
Public MustInherit MyBaseClass
Protected Sub New(paramList)
If paramList IsNot Ok Then Thow New Exception
...
End Sub
End Class