Class versus module in VB

What is the advantage, if any, of using modules over classes in VB? How do they differ from each other and what are the advantages / disadvantages of using modules? In VB or VB.NET, I use both.

+2


a source to share


3 answers


(A) Modules

and

(B) Classes with functions Shared

solve the same problem: both allow you to logically group a set of functions.

Advantages of using the module:



  • It allows you to define extension methods .
  • It will immediately become apparent to someone reading your code that this is not a class representing a group of stateful objects, but only a "function container".

Benefits of using a class with shared functions:

  • It's easy to extend it with instances (= not shared) variables, functions and properties later on.

So, if you're writing a bunch of helper functions and want to group them logically (where the notion of the state of that group just doesn't make sense), use a module - that's exactly what they're here for. On the other hand, if you have a function that conceptually fits into an existing class, add it as a generic function to that class.

+7


a source


The main difference is that methods in modules can be called globally, while methods in classes cannot. So instead, ModuleName.MyMethod()

you can just call MyMethod()

. Whether this is an advantage or a disadvantage depends on the circumstances.



+1


a source


The module has come before, and now VB.NET just allows it to be backward compatible. Modules and class are almost the same. You can call the Module.Function () function directly as it is treated as a Shared

Function in the class. A class that you can define a Shared

Function / Method and optionally instantiate a type Dim c as Class = New Class()

.

Avoid using a module, use a class instead. you'd better write better OOP programming.

0


a source







All Articles