What advantage is there, if any, to using Modules rather than classes in VB? How do they differ, and what advantages/disadvantages are there in using modules? In VB or VB.NET, I use both.
A major difference is that methods in modules can be called globally whereas methods in classes can't. So instead of ModuleName.MyMethod()
you can just call MyMethod()
. Whether that is an advantage or disadvantage depends on the circumstances.
Module are come earlier and now VB.NET just let it for backward compatibility. Modules and Class are nearly same. You can call Module.Function() directly as it treat as Shared
Function in a class. Class you can define Shared
Function/Method and additionally can create an instance like Dim c as Class = New Class()
.
Avoid use of Module, instead use Class. it is good for you to write a better OOP programming.
(A) Modules
and
(B) Classes with only Shared
functions
solve the same problem: Both allow you to logically group a set of functions.
Advantages of using a module:
- It allows you to define extension methods.
- For someone reading your code, it is immediately obvious that this is not a class representing a group of stateful objects but just a "function container".
Advantages of using a class with shared functions:
- It's easy to extend it with instance (= non-shared) variables, functions and properties later on.
So, if you are writing a set of helper functions and want to logically group them (where the concept of a state of this group just doesn't make sense), use a module -- this is exactly what they are here for. On the other hand, if you have a function that conceptually fits to an already existing class, add it as a shared function to that class.