When should or shouldn't a variable be declared as a custom Interface type?
When walking through some code, I required to know what was happening here:
Public Class MyMainProject .... Public Sub DoMyWork() Dim objIMyInterface As IMyInterface .... objIMyInterface = GetReturnObject() End Sub .... End Class
According to what I saw,
objIMyInterface is only being used for one thing. I didn't know how many classes
implement it, but there's no casting of similar types in this code.
objIMyInterface is used just like a regular type, not anonymous in the least. Second of all, my research helped a little...
GetReturnObject happens to return an instance of
IMyInterface. The return object of
GetReturnObject, of course, has a call to another method.
Public Function GetReturnObject() As IMyInterface Dim retObject As IMyInterface ... retObject = AnotherMethod() ... Return retObject End Function
So I try to step into
AnotherMethod, but it's in a project with no symbols. So after some research, I find the source and go through it. After repeating this process a few times, I eventually get to something like this:
Public Function FinalMethod() As IMyInterface Dim FinalObject As MyClassType ... FinalObject = GetMyClassType() ... Return FinalObject End Function
MyClassType! I go to that Class and of course:
Public Class MyClassType Implements IMyInterface ... End Class
What I end up finding out is that
IMyInterface is used by nothing else but this class. No biggie, it's all good code by the looks of it. But then I go back to my original project I notice this:
Public Class MyMainProject .... Public Sub DoMyWork() Dim objIMyInterface As IMyInterface .... objIMyInterface = GetReturnObject() End Sub .... Public Sub OtherWork() Dim objMyType As MyClassType .... End Sub .... End Class
The guy who created this is long gone, but I'd like to know what your thoughts are on which method should be used. Should I declare both as
IMyInterface? Or both as
MyClassType? The code works fine either way.