Search code examples
vb.netinterfacestaticpropertiesdecoupling

How do you handle shared members when dealing with interfaces?


So I did tons and tons of work trying to make an interface for a common set of classes. The idea was to make an interface that each class could use within the set, but ultimately each class is different. Turns out interfaces do not like shared members. What I tried:

Public Interface ISomeInterface
Shared Property Meta() as Object
End Interface


Public Class A

Implements ISomeInterface
Shared Public Property Meta() as Object Implements ISomeInterFace.Meta
'Set/get methods
End Propery

Public Function Haduken() as Object
'perform Haduken
End Function
End Class


Public Class B

Implements ISomeInterface
Shared Public Property Meta() as Object Implements ISomeInterFace.Meta
'Set/get methods
End Propery

Public Function SonicBoom() as Object
'perform sonic boom
End Function
End Class

Obviously, had I done my homework on this, I would have known that shared members can't be use in interfaces. Should I just leave the individual classes completely responsible for handling its shared members? Is there another way to keep coupling down to a minimum with shared members? Theres about 20 something or so classes that will implement a single interface. Thanks in advance.


Solution

  • The simplest way to work around this is to have a Private implementation of the interface which simply forwards to the Shared member

    Public Shared Property Meta As Object
      ' Get / Set methods
    End Property
    
    Private Property MetaImpl() as Object Implements ISomeInterFace.Meta
      Get 
        return Meta
      End Get
      Set
        Meta = Value
      End Set
    End Propery
    

    This pattern allows you to maintain the same public facing API and still implement the interface.