Is it considered an acceptable practice to use Modules instead of Classes with Shared member functions in VB.NET?
I tend to avoid Modules, because they feel like leftover remains from Visual Basic 6.0 and don't really seem to fit in anymore. On the other hand, there doesn't seem to be much difference between using a Module and a Class with only Shared members. It's not that often that I really have much need for either, but sometimes there are situations where they present a simple solution.
I'm curious to hear whether you have any opinion or preferences one way or the other.
The main difference between classes and modules is that classes can be instantiated as objects while standard modules cannot.
What is the difference between a class and a module? Modules are collections of methods and constants. They cannot generate instances. Classes may generate instances (objects), and have per-instance state (instance variables).
Actually, form are just class module that have control placed on form and can we display form windows. Class modules do not have visual component as compare to form module. Standard module: – Standard module are container for procedure and declaration, commonly accessed by other module with in the application.
A Module is not a class. It is a container element, but is not an object. In a Module, all members are shared and have "Friend" accessibility. Some notes. We cannot instantiate a Module—it serves mainly to organize code in a global, single place.
Module
s are VB counterparts to C# static
classes. When your class is designed solely for helper functions and extension methods and you don't want to allow inheritance and instantiation, you use a Module
.
By the way, using Module
is not really subjective and it's not deprecated. Indeed you must use a Module
when it's appropriate. .NET Framework itself does it many times (System.Linq.Enumerable
, for instance). To declare an extension method, it's required to use Module
s.
I think it's a good idea to keep avoiding modules unless you stick them into separate namespaces. Because in Intellisense methods in modules will be visible from everywhere in that namespace.
So instead of ModuleName.MyMethod()
you end up with MyMethod()
popups in anywhere and this kind of invalidates the encapsulation. (at least in the programming level).
That's why I always try to create Class with shared methods, seems so much better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With