VBfx / Common / Modules

Functions

A Module is basically a container for code. So what is it good for? Normally you'd put your functions directly into the Form but what if you want to write more general functions like the following one?

Public Function CompareNames( iName1 as String, iName2 as String ) as Boolean
    CompareNames = StrComp( Name1, Name2, vbTextCompare ) = 0 )
End Function

This function compares the 2 names and returns True if they match, else it returns False. If you put this function into the form directly this will work without any problems. But when adding another form to your project you'll have to copy the function there. This will simply end up in loads of code and if you want to change anything later you'll have to affect any copy of the code and that's just crap.

So how can modules help us to keep code clear? Simply move the function into a module! Modules aren't bound to your form and all contained code that is marked as Public can be accessed from any other form or module within your project. Of course you'll have to decide for each function if it goes into a module or not. One rule is to write as general functions as possible, eg. pass the Form as parameter instead of hard-coding it into a function! You can get into problems if a function changes the properties of a Object or if it uses global variables. What's global variables? Well, just keep on reading!

Global variables

Have you ever wondered how to use a variable in 2 different forms? When I started programming I put Labels onto the form and accessed them from the second one (shame on me). Well this surely works, but that's just crap (but it shows that you can always find a solution). Here again, Modules will help us out and it's nearly the same as with functions: Just put your variable into the module instead of declaring it in the form directly. Doesn't work you say? Well that's because the declaration is a little different.

Public PlayerName as String

While you use Dim or Private (both is the same) to declare a private variable you need to use Public in a module to allow other forms to access it. It's the same as we had with functions before. Wonder why you should use Private at all? Well this is called information hiding, meaning you can hide code that is for module-internal use only. Note that private functions and variables are still accessible from within the module itself! This'll be helpfull later in programming when modules grow and you need to keep your code clear.

Navigation