Question Enforce "contract" without using an Interface

Joined
May 28, 2010
Messages
5
Programming Experience
5-10
I have a situation where I need to make sure that a class implements a set of Shared methods. The context is quite complex, so I'll spare the details.

I basically have an abstract class that deals heavily with Generics. I need to call a Shared method on the Generic class T. I need to make sure the Shared method is implemented.

I could use reflection to check for the implementation and call the method if it exists or throw an exception otherwise. However, since the derived class is not "aware" that it needs to implement this method, I feel that the exception will get thrown more often than not.

Having the derived class also implement an Interface and force this via constraints placed on T in the abstract class would work great, except that the method has to be Shared, which rules out using an Interface. However, this type of logic should give you a good idea of what I'm trying to accomplish:

VB.NET:
Public MustInherit Class MyAbstractClass(Of T As ISomeInterface)
...
     T.Bar() 'THIS IS BETTER THAN REFLECTION
...
End Class

Public Interface ISomeInterface
     Sub Bar() 'I NEED THIS TO BE SHARED
...
End Interface

Public Class Foo
     Implements ISomeInterface
...
     'THE FOLLOWING IS NOT POSSIBLE BECAUSE Interfaces DON'T DO Shared
     Public Shared Sub Bar() Implements ISomeInterface.Bar
...
     End Sub
End Class

Public Class MyDerivedClass
     Inherits MyAbstractClass(Of Foo)
...
End Class

In conclusion, is there a way to enforce an "Interface-like contract" on a class without using an Interface, so that you can force a Shared method to be implemented?
 
It's a bit of a hack and I'm not 100% sure that it would work, but I think you could declare the Shared method in a base class, constrain the generic type parameter to that type and then Shadow the method in each derived class.
 
Thanks, that indeed will work to solve the problem I presented. However, I am actually looking for a way to force the developer who is implementing MyAbstractClass to implement Bar(). While shadowing the Shared method gives the developer the opportunity to implement Bar(), it will not force him/her to do so, and the developer may not be aware that the opportunity exists.

My ultimate goal is to make sure the developer knows that he/she can implement Bar() and does not forget to do so. The relationship an Interface provides is exactly what I am looking for, but it doesn't work if the method is Shared.

There are alot of posts on the Net about why Interfaces should or should not allow a Shared implementation, and I fully understand why they shouldn't. Even if they should, they don't. I'm just looking for an equivalent type of structure such as "Public Shared MustImplement Sub Bar()".

Any ideas on how to achieve something like this are welcome and greatly appreciated.
 
Back
Top