Late Binding in VB - vb.net

From what I have read so far, late binding is defining a variable as Object and then assigning it to the actual object later which is actually done at run time. I don't understand the point to that. Maybe this is the Java in me, but doesn't that limit the functionality to what is just in Object? It is like saying, "I want the potential of the extra stuff, but I don't want to have access to it." Is there an actual purpose for late binding in VB, or Java for that matter, that I'm overlooking?

You have it backwards. By using early binding you are limiting yourself to just the members of the type of the variable. With Option Strict On, a variable declared as type Object will only allow you access to members of type Object, regardless of the type of the actually object it refers to. With Option Strict Off, you can access a member of any name on a variable of type Object and the compiler won't complain. It's only at run time that any type checking is done so, as long as the actual object assigned to the variable has a member with that name, the code will run.
Probably the most common use for late binding is Office Automation. There are other options now but, in the past, if you referenced an Office library and used the specific types it contained, facilitating early binding, then you were limited to that specific version of Office. In order to support multiple versions, you had to forgo the reference, declare all your variables as type Object and use late binding. As long as the version of Office present at run time included the specified members on the objects used, the code would run without issue.
By the way, late binding doesn't require using type Object, although it is probably the most common. It just means that the reference is a less derived type than the object and you use a member of the object's type that the reference's type doesn't have, e.g. you use type Control and then use a member specific to type Button.

What I seen - some early .NET adapters-developers were doing is - they were using late binding instead on interfaces. They would declare two or more types
Public Class Handler1
Public Sub Execute()
' do something
End Sub
End Class
Public Class Handler2
Public Sub Execute()
' do something else
End Sub
End Class
And they would stick this thing into session object
If someting = 1 Then
Session("Handler") = New Handler1()
Else
Session("Handler") = New Handler2()
End If
And then, to process something they would do
Session("Handler").Execute()
There we go. This is not pretty or smart. But that was instead of proper programming like this (Imagine handlers implement IHandler interface with method Execute)
Dim h As IHandler = TryCast(Session("Handler"), IHandler)
If h IsNot Nothing Then
h.Execute()
End If
Here is where downfall of late binding starts: In the case of late binding, someone, somewhere, can rename a method Execute and compile code nicely. Release. And only then, at runtime, get a problem.
Late binding was good when we used to deal with interop and COM. Other than this, it is detrimental.

Related

Late Binding: Expecting error but not getting it

I wrote the below code to understand Late Binding with Option Strict ON. With OPTION STRICT ON, I was expecting an error in the statement: o = New Car(). But not getting any error. Isn't that strange? Its clearly mentioned in the MSDN documentation on Option Strict that when ON it prevents late binding - gives a compile time error. So what is happening here....can someone pls help?
Option Strict On
Module Module1
Sub Main()
Dim o As Object
o = New Car() 'Expecting error here but not getting
Console.ReadLine()
End Sub
End Module
Class Car
Public Property Make As String
Public Property price As Integer
End Class
There's nothing at all wrong or inappropriate about assigning an object of a derived type to a variable of a base type. That's exactly what allows for polymorphism, which is a cornerstone of OOP. What constitutes late binding is trying to access a member of the derived type via a reference of the base type.
The compiler only knows the type of the reference, so it only knows about members of that type. If you try to access a member that doesn't belong to that base type type then the compiler cannot confirm that that access is valid. Type-checking must be deferred until run time, when the type of the object is determined and it is confirmed whether that member actually exists.
Early binding is when the the existence of a member on a type is confirmed at compile time, while late binding is when it's done at run time. If there is no member access then there is no binding at all to be early or late.
Dim c As New Car
Dim o As Object = New Car
c.Make = "Ford" 'Early binding
o.Price = 20000 'Late binding
In the code above, the setting of the Make property is early-bound because Make is a member of the type of c. On the other hand, the setting of Price is late-bound because Price is not a member of the type of o so confirmation that the object has such a member must be deferred until run time.

Do I understand not using getters and setters correctly

After reading this piece by Yegor about not using getters and setters, it sounds like something that makes sense to me.
Please note this question is not about whether doing it is better/worst, only if I am implementing it correctly
I was wondering in the following two examples in VBA, if I understand the concept correctly, and if I am applying it correctly.
The standard way would be:
Private userName As String
Public Property Get Name() As String
Name = userName
End Property
Public Property Let Name(rData As String)
userName = rData
End Property
It looks to me his way would be something like this:
Private userName As String
Public Function returnName() As String
returnName = userName
End Function
Public Function giveNewName(newName As String) As String
userName = newName
End Function
From what I understand from the two examples above is that if I wanted to change the format of userName (lets say return it in all-caps), then I can do this with the second method without changing the name of the method that gives the name through - I can just let returnName point to a userNameCaps property. The rest of my code in my program can still stay the same and point to the method userName.
But if I want to do this with the first example, I can make a new property, but then have to change my code everywhere in the program as well to point to the new property... is that correct?
In other words, in the first example the API gets info from a property, and in the second example the API gets info from a method.
Your 2nd snippet is neither idiomatic nor equivalent. That article you link to, is about Java, a language which has no concept whatsoever of object properties - getFoo/setFoo is a mere convention in Java.
In VBA this:
Private userName As String
Public Property Get Name() As String
Name = userName
End Property
Public Property Let Name(rData As String)
userName = rData
End Property
Is ultimately equivalent to this:
Public UserName As String
Not convinced? Add such a public field to a class module, say, Class1. Then add a new class module and add this:
Implements Class1
The compiler will force you to implement a Property Get and a Property Let member, so that the Class1 interface contract can be fulfilled.
So why bother with properties then? Properties are a tool, to help with encapsulation.
Option Explicit
Private Type TSomething
Foo As Long
End Type
Private this As TSomething
Public Property Get Foo() As Long
Foo = this.Foo
End Property
Public Property Let Foo(ByVal value As Long)
If value <= 0 Then Err.Raise 5
this.Foo = value
End Property
Now if you try to assign Foo with a negative value, you'll get a runtime error: the property is encapsulating an internal state that only the class knows and is able to mutate: calling code doesn't see or know about the encapsulated value - all it knows is that Foo is a read/write property. The validation logic in the "setter" ensures the object is in a consistent state at all times.
If you want to break down a property into methods, then you need a Function for the getter, and assignment would be a Sub not a Function. In fact, Rubberduck would tell you that there's a problem with the return value of giveNewName being never assigned: that's a much worse code smell than "OMG you're using properties!".
Functions return a value. Subs/methods do something - in the case of an object/class, that something might imply mutating internal state.
But by avoiding Property Let just because some Java guy said getters & setters are evil, you're just making your VBA API more cluttered than it needs to be - because VBA understands properties, and Java does not. C# and VB.NET do however, so if anything the principles of these languages would be much more readily applicable to VBA than Java's, at least with regards to properties. See Property vs Method.
FWIW public member names in VB would be PascalCase by convention. camelCase public member names are a Java thing. Notice how everything in the standard libraries starts with a Capital first letter?
It seems to me that you've just given the property accessors new names. They are functionally identical.
I think the idea of not using getters/setters implies that you don't try to externally modify an object's state - because if you do, the object is not much more than a user-defined type, a simple collection of data. Objects/Classes should be defined by their behavior. The data they contain should only be there to enable/support that behavior.
That means you don't tell the object how it has to be or what data you want it to hold. You tell it what you want it to do or what is happening to it. The object itself then decides how to modify its state.
To me it seems your example class is a little too simple to work as an example. It's not clear what the intended purpose is: Currently you'd probably better off just using a variable UserName instead.
Have a look at this answer to a related question - I think it provides a good example.
Regarding your edit:
From what I understand from the two examples above is that if I wanted
to change the format of userName (lets say return it in all-caps),
then I can do this with the second method without changing the name of
the method that gives the name through - I can just let returnName
point to a userNameCaps property. The rest of my code in my program
can still stay the same and point to the method iserName.
But if I want to do this with the first example, I can make a new
property, but then have to change my code everywhere in the program as
well to point to the new property... is that correct?
Actually, what you're describing here, is possible in both approaches. You can have a property
Public Property Get Name() As String
' possibly more code here...
Name = UCase(UserName)
End Property
or an equivalent function
Public Function Name() As String
' possibly more code here...
Name = UCase(UserName)
End Function
As long as you only change the property/function body, no external code needs to be adapted. Keep the property's/function's signature (the first line, including the Public statement, its name, its type and the order and type of its parameters) unchanged and you should not need to change anything outside the class to accommodate.
The Java article is making some sort of philosophic design stance that is not limited to Java: The general advise is to severely limit any details on how a class is implemented to avoid making one's code harder to maintain. Putting such advice into VBA terms isn't irrelevant.
Microsoft popularized the idea of a Property that is in fact a method (or two) which masquerade as a field (i.e. any garden-variety variable). It is a neat-and-tidy way to package up a getter and setter together. Beyond that, really, behind the scenes it's still just a set of functions or subroutines that perform as accessors for your class.
Understand that VBA does not do classes, but it does do interfaces. That's what a "Class Module" is: An interface to an (anonymous) class. When you say Dim o As New MyClassModule, VBA calls some factory function which returns an instance of the class that goes with MyClassModule. From that point, o references the interface (which in turn is wired into the instance). As #Mathieu Guindon has demonstrated, Public UserName As String inside a class module really becomes a Property behind the scenes anyway. Why? Because a Class Module is an interface, and an interface is a set of (pointers to) functions and subroutines.
As for the philosophic design stance, the really big idea here is not to make too many promises. If UserName is a String, it must always remain a String. Furthermore, it must always be available - you cannot remove it from future versions of your class! UserName might not be the best example here (afterall, why wouldn't a String cover all needs? for what reason might UserName become superfluous?). But it does happen that what seemed like a good idea at the time the class was being made turns into a big goof. Imagine a Public TwiddlePuff As Integer (or instead getTwiddlePuff() As Integer and setTwiddlePuff(value As Integer)) only to find out (much later on!) that Integer isn't sufficient anymore, maybe it should have been Long. Or maybe a Double. If you try to change TwiddlePuff now, anything compiled back when it was Integer will likely break. So maybe people making new code will be fine, and maybe it's mostly the folks who still need to use some of the old code who are now stuck with a problem.
And what if TwiddlePuff turned out to be a really big design mistake, that it should not have been there in the first place? Well, removing it brings its own set of headaches. If TwiddlePuff was used at all elsewhere, that means some folks may have a big refactoring job on their hands. And that might not be the worst of it - if your code compiles to native binaries especially, that makes for a really big mess, since an interface is about a set of function pointers layed out and ordered in a very specific way.
Too reiterate, do not make too many promises. Think through on what you will share with others. Properties-getters-setters-accessors are okay, but must be used thoughtfully and sparingly. All of that above is important if what you are making is code that you are going to share with others, and others will take it and use it as part of a larger system of code, and it may be that these others intend to share their larger systems of code with yet even more people who will use that in their even larger systems of code.
That right there is probably why hiding implementation details to the greatest extent possible is regarded as fundamental to object oriented programming.

How to limit the scope of a variable to the function when declared in an If statement

I need to limit the scope of a variable to the function it resides with however I need to declare it within an if statement as it's type will change depending. I'm working within VB.NET
Public Function CourseDataTable()
If RadioCourses.Checked Then
Dim SearchBy As New classSearchCourses
ElseIf RadioAttendees.Checked Then
Dim SearchBy As New classSearchAttendees
End If
The obvious problem is that the variable doesn't persist outside of the if statement. I want to limit the scope of this variable because a, it's used else where and b, memory leakage, the class could very well end up holding whole SQL tables and I don't want that persisting when it's not needed.
I can't use inheritance or polymorph here because I'm working a legacy system.
This is probably a rework (I'm struggling think of a different way of approaching it evidently) as I can't find anything in MSDN that allows procedure scope but ignores any other blocks at declaration.
It is still possible to use polymorphism in a legacy system. What you can do is find the common functionality that must exist between the two in order for you to even want to reuse the same variable. Then you can create wrapper classes for each of these legacy classes. The wrapper class would implement the common interface and simply call the underlying legacy implementation. Then you simply declare a variable to that common Interface and create the appropriate wrapper class instance inside of the if statements.
Edit: If you have the ability to modify the legacy classes at all, a simpler solution would be to simply create a common Interface that both of the legacy classes can implement. This will give you the polymorphic functionality that you desire without the need of wrapper classes. VB.Net even provides the ability to implement an interface in a way to where the interface methods are only exposed by a Interface reference. To do this, you simply mark the interface implementation methods as Private.
You could just declare SearchBy as Object and then do something like this
Dim searchBy As Object
If RadioCourses.Checked Then
searchBy = New classSearchCourses
ElseIf RadioAttendees.Checked Then
searchBy = New classSearchAttendees
End If
If searchBy.GetType() Is GetType(classSearchCourses) Then
'Do something
ElseIf searchBy.GetType() Is GetType(classSearchAttendees) Then
'Do something else
End If
This is still inheritance though since most everything inherits from System.Object but it will save you declaring your own new base class if for some reason you can't do that

vb.net reflection vs. late binding?

What should be more proper or what is recommended to use in VB.NET from either reflection vs. late binding:
'Type can be various objects that have a common property for sure.'
Dim type = sender.GetType()
Dim prop = type.GetProperty("Text", 20)
Dim value = property.GetValue(sender, Nothing)
versus:
Dim value = sender.Text
Under the covers they are both doing the same thing (relatively speaking). VB.NET's late-binding feature is done via assembly metadata queries at runtime which is exactly what reflection is all about.
One of the benefits to your first approach is that you have an opportunity to handle errors in a more finely-grained manner.
Isn't sender.Text always a string though? So the type of value can be inferred at compile time, making the latter an example of early binding?
If you do use late binding, you can put the method that extracts the properties into a partial class with Option Explicit = Off. That way, you still have type checking in the rest of your code.

Access private member variable of the class using its object (instance)

Here is a VB.NET code snippet
Public Class OOPDemo
Private _strtString as String
Public Function Func(obj as OOPDemo) as boolean
obj._strString = "I can set value to private member using a object"
End Function
End Class
I thought we cannot access the private members using the object, but perhaps CLR allows us to do that. So that means that access modifiers are based on the type and not on the instance of that type. I have also heard that c++ also allows that..
Any guesses what could be the reason for this?
Edit:
I think this line from the msdn link given by RoBorg explains this behaviour
"Code in the type that declares a private element, including code within contained types, can access the element "
Your question is quite confusing but I think I've understood it as:
"Why can I access another instance (of my class)'s private variables?"
And you're right - in all OOP languages I've used you can access private variables from other instances, precisely because access permissions are based on where the code is, rather than to which object instance it 'belongs'.
It might be hard to implement copy constructors or equality operators otherwise.
Here's the section about access levels in MSDN.