Classes vs. Modules in VB.NET
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.
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.
Modules are by no means deprecated and are used heavily in the VB language. It's the only way for instance to implement an extension method in VB.Net.
There is one huge difference between Modules and Classes with Static Members. Any method defined on a Module is globally accessible as long as the Module is available in the current namespace. In effect a Module allows you to define global methods. This is something that a class with only shared members cannot do.
Here's a quick example that I use a lot when writing VB code that interops with raw COM interfaces.
Module Interop
Public Function Succeeded(ByVal hr as Integer) As Boolean
...
End Function
Public Function Failed(ByVal hr As Integer) As Boolean
...
End Function
End Module
Class SomeClass
Sub Foo()
Dim hr = CallSomeHrMethod()
if Succeeded(hr) then
..
End If
End Sub
End Class
It is acceptable to use Module
. Module
is not used as a replacement for Class
. Module
serves its own purpose. The purpose of Module
is to use as a container for
- extension methods,
- variables that are not specific to any
Class
, or - variables that do not fit properly in any
Class
.
Module
is not like a Class
since you cannot
- inherit from a
Module
, - implement an
Interface
with aModule
, - nor create an instance of a
Module
.
Anything inside a Module
can be directly accessed within the Module
assembly without referring to the Module
by its name. By default, the access level for a Module
is Friend
.