I am not sure how clear my question is by the title, but I am trying to make Class methods instead of Instance methods in Visual Basic that way I don't have to waste memory and code creating temporary objects to execute methods that don't need instance variables.
I am not sure if you can do that in VB but I know you can in Objective-C by using either a "+" or "-" sign in front of the method declaration. And in C++ (at least I think, I can't remember) you put the static keyword or const keyword in front of the function.
How would I do this in VB if it is possible? Or should I just make a separate set of functions that are not members of a class?
If you are looking to define class methods in VB.Net you just need to add the Shared modifier to the function
Class C1
Public Shared Function DoSomething() As String
' Insert code here
End Function
End Class
As to whether or not you should use a class method over an instance method to avoid allocations. I think you're using the wrong reasoning pattern here. I would start simply with design the class to have the most natural and straight forward API. Then after that process if a profiler shows that allocation of small objects is a problem update the API to account for this.
Making an API design decision for performance reasons without using a profiler will almost surely lead to wasted effort.
You want to create a Shared method in VB.net.
Related
I'm tying to implement a novel way of overriding functions based on which DLLs I have loaded. In this model, I have a list of class instances from First = Highest Priority to Last = Lowest priority.
Any of those classes may implement a Hook function or callback. I'm currently at the stage where I can pass a string to a function, and then call it - my library convention looks like this:
Dim hookclasses as HooksList
Dim callable as Object
hookclasses.Add(new ClassA)
hookclasses.Add(new ClassB)
'... etc.
if hookclasses.Has("MyHookFunction", callable) then
callable.MyHookFunction()
end if
This all works, but I'd like to reduce typos by leveraging Intellisense. I've already thought of popping the strings into a class containing constant strings, so I'm after something better than that.
Ideally I'd like to have a fallback class that implements all of the hook functions (even if it simply returns), and if the language supported it, I'd like to do the following:
if hookclasses.Has(NameOf(FallbackClass.MyHookFunction), callable) then ...
Clearly there is no 'NameOf' operator, and I don't know how to write a NameOf function.
Is this possible?
Thanks.
Check this article nameOf (C# and Visual Basic reference)
https://msdn.microsoft.com/en-us/library/dn986596.aspx
It does exactly what you want. And before that String Litterals were almost the only option.
Edit :
Question was : "Clearly there is no 'NameOf' operator, and I don't know how to write a NameOf function."
If I understand your problem right, you have a list of classes that you fetched from dynamically loaded DLL, point is you don't know if a class implements all of the hooks or only a few.
If you use an interface, like IHookable and put all the hook functions in there, it means all the DLL have to implement all the hook functions, which is not what you want.
And (if I understand it properly) if the first class in list does not implement the hook, you check the second one and so on. So with an interface you wouldn't know if the hook is implemented or not.
Beginner question: In a VB.net development environment, is it safe to assume the word "method" eventually refer us to the concept of functions or subroutines?
Eventually function is a block of instructions, created for modular programming purposes. It may have arguments that get passed into it and it certainly has to return something. Subs are likewise with no returns.
Excuse my ignorance but I'm just starting out to learn VB.net.
In the OOP world, a "method" is technically a function or sub that is associated with a class.
For example:
Public Class [MyClass]
Public Sub MyMethod()
End Sub
End Class
MyMethod() is a method. If the sub was outside the class, it'd just be called a Sub or Function
You may hear other programmers refer to a method that is outside a class, but that is technically not correct.
Kind Of.
In Object Orientation, a method must belong to a class
However, VB.Net still allows Modules which are a hangover from procedural days, although these are implemented under the hood as static classes.
But the other way around, a method must be implemented as either a Sub (which has no return value and implies side-effects), or a Function (which has a return value, and in theory implies no side effects), if you follow CQS style convention.
Assuming VB.net doesn't throw away general standards, a method is what you defined as a function or subroutine, but is attached to a particular object.
See this SO post for more information on the difference between methods and functions.
I just did some researches on google but I didn't find an answer to my question.
Is there a way to get the list of the active objects (instances of classes) at runtime?
In my application I need to have single instance classes that needs to be used by different running forms but if I create an instance in the form A, ho do i get control of the same instance in the form B?
Thank you
Actually, your question has 2 parts:
1. How to create single-instance objects.
2. How to have the same object accessible from different forms.
Fortunately for you, there is a solution to both of these problems in one simple and common design pattern called Singleton.
Classes written in the Singleton pattern can only have a single instance, and as you are about to see, as a side effect, this instance is accessible through the entire application.
The simplest way to use the singleton design pattern is this:
Public Class SingletonClass
Private Shared _instance As SingletonClass
Public Shared Function GetSingletonClass() As SingletonClass
If isNothing(_instance) Then
_instance = New SingletonClass()
End If
Return _instance
End Function
Private Sub New()
'' Create the instance here
End Sub
End Class
As you can see, since the constructor is private, it is not accessible from anywhere outside of class SingletonClass, and since class SingletonClass holds a static reference to it's instance, it means that every time you write SingletonClass.GetSingletonClass() in your application you get the same instance.
This design pattern solves both of your problems in a simple, elegant, and well known architecture.
Update
I've recently read a great article about different ways to implement singleton patterns. It turns out that my above specific implementation is not so good, as it is not thread safe. The code examples in this article are C#, but it should be very easy to change them to VB.Net. If you are using .Net 4 or higher, I would recommend going with the 6th version - using .NET 4's Lazy type.
It is both thread safe and lazy loading, two advantages that the implementation I've written doesn't have.
I have developed a Data Access Layer for an application that connects to Oracle and SQL databases. I have written a similar class to that provided by Application Blocks here: http://www.sharpdeveloper.net/source/SqlHelper-Source-Code-cs.html.
I am not sure why the methods are static in the link. When I want to perform a CRUD operation I create an instance of the class and then call the appropriate function. Why are the methods static?
VB.NET does not allow for Shared classes (only shared functions). Therefore I was thinking about making all the functions Shared. Before I do this I want to understand why the methods in the link are static.
I have researched this. For example, the following link explains that the methods are static but does not explain why: https://web.archive.org/web/20210304123854/https://www.4guysfromrolla.com/articles/062503-1.aspx.
A couple of big reasons spring to mind.
Simplicity
Everything you need to run that method arrives via the parameter list. Developers don't have to follow any quirks of an instantiated implementation.
Speed.
According to the following link, static method calls are about 4-5 times faster than their instanced equivalent.
http://msdn.microsoft.com/en-us/library/ms973852.aspx
In vb a module behaves as a static class does in c#. Useful when you just want a helper type class with all shared methods.
As a very general rule static/shared methods should be more efficient. As you do not need to instantiate a class to make the same call. So you aren't generating an entire object to do something that you don't need a full object to do. For example, a simple math function.
public shared function AddNumbers(number1 as integer, number2 as integer) as integer
versus something that modifies or accesses object data.
public function AccrueInterest() as integer
which might be something that accesses an interestRate and Balance property on the same object.
I am new to vb.net and very frustrated.
Like all good programmers I want to split my code into separate files based on functionality . Some of my code interacts with users via Forms and some interacts with lab equipment behind the scenes (no direct user interaction). Sometimes a user will change something that will impact the lab equipment and sometimes something will happen with the lab equipment that a user needs to be aware of. When I use VS to create files I have to choose a Module or Form. VS then creates an empty file with a with either
Public Class Foo
End Class
or
Module Foo
End Module
If I have a bunch of files, each a Module, and if I define routines in a Module to be Friend then I can call them from other Modules, so:
Module Foo
Friend Sub DoSomeWork()
End Sub
End Module
Code in Fee can call routines in Foo -
Module Fee
Friend Sub Stuff()
DoSomeWork()
End SUb
End Module
When I create a Form, VS creates a Class. I find that I can call subroutines defined in a Module from a Class but when I try to call from a Module into a Class I get an error that the routine I am trying to call is not declared. I also cannot call from one Class into another Class. Declarations seem to apply only to library routines outside my program.
I have looked through several online explanations and tutorials, but frankly I don't understand these nor do I care about "inheriting from the base class" and all the other gobbledygook that such "explanations" contain. I want to concentrate on building my application.
My Main form has the name "Main"
I tried putting all the module code into the Main Class first by renaming "Module Foo" to "Public Partial Class Main" - bad idea - creates an impossible-to-find duplicate error. I tried creating empty code files, defining them as Public Partial Class Main and putting the Module code into them, - this worked in that code in the Class Main could call the "Module" code (which was now in Main) and vice-versa, but, other Forms (of course I have more than one) are created by VS to have their own Classes and once the "Module" code is moved out of Modules into Class Main the other Forms(Classes) could not call the code anymore.
I just want some recipe (best practice) I can follow to for defining Modules and Classes so that code and data can be shared.
ANSWER from below
To invoke a subroutine in another Class you simply need to put the class name in front of the subroutine name.
So not
DoSomeWork()
but
Foo.DoSOmeWork()
This may be obvious to all of you experienced programmers but not to me. You do not have to prepend a class/module name to a Module-to-Module call or a Class-to-Module call, only to calls that are made into Classes. Personally, for the sake of consistency, I think the things should be the same, but it would probably violate some OO rule. Anyway thank you to all.
Generally, if you have a function that needs to be called from more than one form, or from forms and modules, put it in the main module. If you have an exceptional case and need to call a function or sub in a form from another form or a module, you can declare it to be public:
Public Class Form1
public sub test(i as integer)
...
end sub
end class
and then you can call it by referring to the class.subname:
call form1.test(7)
NomD,
Like all good programmers
you should indeed care
about "inheriting from the base class" and all the other gobbledygook that such "explanations"
This will make you a better programmer and taking the time to understand why proper code structuring is important will also begin to yield better results for you.
I am not sure why two commentors seem to have an issue with VB.Net. The question would be the same regardless of the language, since both are C# and VB are built on .Net. Code can be written poorly in C#, just like VB. Please leave the language wars at home. NormD, the answer to your question should really be to direct you to the resources needed to better understand the problem. Here is an article on scope that might help a bit - class scope. The reason you are getting the behavior that you see is due to what you are working with. Modules (similar to static classes in C#) are created when you program begins, so there is no need to create them. So you can reference a method on a module, like so - module.method. Classes on the other hand, some exceptions, need to be created in order to be referenced. So to use an employee (or form class) you must create a variable of that class. So you would use dim myemp as New Employee() and then call myemp.method() from your module. This is a rather simplistic description, so please read the scope article and other MSDN articles for more information. I am sure other posters can post additional links with good information. Hope this helps a bit.
Wade
It seems like you don't understand the basics of object-oriented programming (OOP).
If you DON'T want to learn how to design your application in an object-oriented way, then only create modules in your application and you will be able to call functions from one to another without any problem. But this will result in code that will not be easily maintainable and scalable.
The other option is to learn OOP by picking a book about it, or following a course or tutorial on the subject. It's a significant investment but it will result in more robust code that will scale better when your application grows.