Results 1 to 32 of 32

Thread: Global vs Public

  1. #1

    Thread Starter
    PowerPoster Pasvorto's Avatar
    Join Date
    Oct 2002
    Location
    Minnesota, USA
    Posts
    2,951

    Global vs Public

    I came from a COBOL/PASCAL background. I am used to Global variables. My VB apps use Global variables. I have been reading that I should not use GVs. I should, instead, use PUBLIC variables.

    If I go to my modules and change all the GLOBAL variable definitions to PUBLIC defintions, what will I gain (what will I lose)?

    I use them as a vehicle for storing data as I transfer between forms when I don't want to leave the previous form open.

  2. #2
    Fanatic Member Bombdrop's Avatar
    Join Date
    Apr 2001
    Location
    St Helens, England, UK
    Posts
    667
    As far as i know there is no differeance in Gloabal and Public variables, I was of the belief that Global was just a throw back from older versions of BASIC.


    Hope this helps !!

  3. #3
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    35,239
    I would guess that the only problem with global is that it is considered old, and therefore, bad form.

    Very easy to change them over, though, since you can search and replace on the word.

  4. #4

    Thread Starter
    PowerPoster Pasvorto's Avatar
    Join Date
    Oct 2002
    Location
    Minnesota, USA
    Posts
    2,951
    I just finished doing that. I will see if there is any performance gain.

  5. #5
    Fanatic Member Bombdrop's Avatar
    Join Date
    Apr 2001
    Location
    St Helens, England, UK
    Posts
    667
    There is as far as i know no performance, but for others to use use and understand your code with more ease declaring Public is advisable.

    Hope this helps!!

  6. #6
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    35,239
    If you do find any performance differences, please post them, I'd be interested to hear about that.

  7. #7
    PowerPoster Dave Sell's Avatar
    Join Date
    Mar 2004
    Location
    /dev/null
    Posts
    2,961

    Re: Global vs Public

    Originally posted by Pasvorto
    I came from a COBOL/PASCAL background. I am used to Global variables. My VB apps use Global variables. I have been reading that I should not use GVs. I should, instead, use PUBLIC variables.

    If I go to my modules and change all the GLOBAL variable definitions to PUBLIC defintions, what will I gain (what will I lose)?

    I use them as a vehicle for storing data as I transfer between forms when I don't want to leave the previous form open.
    Public variables on a Form is considered BAD OO PROGRAMMING PRACTICE.

    Instead, make Private data members and give them Public Property Accessors/Mutators:

    VB Code:
    1. Option Explicit
    2. '
    3. Private m_blnDidErrorOccur As Boolean
    4. '
    5.  
    6. Public Property Get ErrorOccurred() As Variant
    7.     ErrorOccurred = m_blnDidErrorOccur
    8. End Property
    9.  
    10. Public Property Let ErrorOccurred(ByVal vNewValue As Variant)
    11.     m_blnDidErrorOccur = vNewValue
    12. End Property

  8. #8
    PowerPoster Dave Sell's Avatar
    Join Date
    Mar 2004
    Location
    /dev/null
    Posts
    2,961
    Er, the above won't work in a module, only a Form or a Class, sorry.

    However, Global/Public varaiables in a module are not good OO Design practices. I too come from a long history of global vaiables in BASIC and C. However, I have not had a Global variable in ANY project in the last 5 years, and I never miss them.

    Alot has to do with your theroy of OO Design, and wether or not you implement your project in an OO way. If you are using Global Variables, that is a red flag that you are not being OO.

  9. #9
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    CT
    Posts
    17,882
    Originally posted by Dave Sell
    Er, the above won't work in a module, only a Form or a Class, sorry.

    However, Global/Public varaiables in a module are not good OO Design practices. I too come from a long history of global vaiables in BASIC and C. However, I have not had a Global variable in ANY project in the last 5 years, and I never miss them.

    Alot has to do with your theroy of OO Design, and wether or not you implement your project in an OO way. If you are using Global Variables, that is a red flag that you are not being OO.
    I also come from a long history of other hardware platforms and languages - only been doing VB for three years now.

    Let's say you had lots of child forms - each doing maintenance on different tables in your database. Let's say you wanted to keep track of every "lookup" value that was used to select records for maintenance.

    Child forms could close and be re-opened.

    Where would you store that information in VB?

  10. #10
    PowerPoster Dave Sell's Avatar
    Join Date
    Mar 2004
    Location
    /dev/null
    Posts
    2,961
    In a Property on the Main Form.

  11. #11
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    CT
    Posts
    17,882
    Explain property?

    Let's make it simple - it's a pair of information - a string the describes what "table element was used" and another string that says what data value. Something like "NAME with SMITH" or "ID with 1234".

    Would you put a collection into the main form and pop them into that?

  12. #12
    PowerPoster
    Join Date
    Feb 2001
    Location
    Crossroads
    Posts
    3,047
    I vaguely remember that there is some difference in behavior between Global and Public when acessing variables that belong to a VBA project that is referenced by the VBA project you are currently coding in. I seem to remember that there was a reason to use Global in that case.

    Anyone know what I am almost remembering here?

  13. #13
    PowerPoster Dave Sell's Avatar
    Join Date
    Mar 2004
    Location
    /dev/null
    Posts
    2,961
    Refer to my example of the Boolean Property above.

    Yes, I use a "Collection-Type" Properties all the time:


    VB Code:
    1. ' This is frmMain.frm
    2. Option Explicit
    3. '
    4. Private m_colChildEntries As Collection
    5. '
    6.  
    7. Private Sub Form_Load()
    8.     Set m_colChildEntries = New Collection
    9. End Sub
    10.  
    11. Private Sub Form_Unload(Cancel As Integer)
    12.     Set m_colChildEntries = Nothing
    13. End Sub
    14.  
    15. Public Property Get Entries() As Collection
    16.     Set Entries = m_colChildEntries
    17. End Property

    Notice I have a read-only Collection Property in this case.

    VB Code:
    1. ' This is in frmChild.frm
    2. Option Explicit
    3. '
    4.  
    5. Private Sub MakeEntry()
    6.   ' Do whatever it is you do...
    7.   frmMain.Entries.Add "Some kind of variable, or even an Object here...", "This can be a unique ID value"
    8. End Sub

    Notice that I have used the default Collection Object in this case which exposes the .Add Property of itself, which may not be as feature-rich as your requirements.

    Please be aware that you have the ability to create your own Collection-Type Classes (Collections on Steroids) and are free to expose them instead of a standard Collection Object should the standard Collection Object not have all the features you need.

    The point is, there has been a strong movement in the last 10 years to move toward OOP and OOD, but people are slow to pick up on the trends. I have embraced them and champion them whenever I can.
    Last edited by Dave Sell; Sep 15th, 2004 at 11:31 AM.

  14. #14
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    CT
    Posts
    17,882
    Thanks for the clarification. I appreciate "black-box" coding concepts and ACID techniques - I've been programming for nearly 30 years now...

    But part of me says that a PUBLIC collection with a function or two that adds and drops entries into in - in some BASMAIN module, isn't a whole lot different than what you describe.

    Same concept - just different syntax.

    Maybe someday I'll have more time to explore the methods you describe.

    Thanks again.

  15. #15

    Thread Starter
    PowerPoster Pasvorto's Avatar
    Join Date
    Oct 2002
    Location
    Minnesota, USA
    Posts
    2,951
    This is a very interesting discussion. I use very limited OOP techniques. Encapsulation (pseudo) is about as close as I come. I wish I had the time to attend a class on OOP and Classes, but, being a one man shop, I don't. So, I muddle on, reading what I can and listening(?) to discussions such as this.

    Since upgrading to ADO and SQL Server 2K, I have been able to change my code to open, close, and set (to nothing) recordsets as I need them. That has improved things. I am moving as much "repeatable" code as I can to "global" subroutines. As you can see, I am on a quest to get my code (which has migrated from VB3 over the last 10 years) optimized for SQL Server and VB6 (before I even think about .NET).

    So, keep up the good discussion. Folks at my levels have tons to learn from you guys.

  16. #16
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    35,239
    Keep in mind that mandating strict adherence to a form is always a bad design principle. That is putting form over function, which is a mistake in any design.

    There is a real cost to making private variables accessed via Get/Set pairs, regardless of platform. A clever compiler could take such a thing in C++, if the function was inlined, and implicitly allow direct access to the variable, but unless that happens, there will be call overhead.

    This is one of the reasons that you still see global variables in places where speed is essential (graphics).

    Secondly, how you use variables depends to some extent on who will be reading the source. There is absolutely no value to OO design or any of its principles if you can be certain that nobody will ever have reason to go back to that source code. Since that is an unlikely assertion, there is usually value to OO, but keep that edge case in mind.

    If you are the only person who will ever look at your source code, you can use globals without a care in the world. After all, they will be faster in VB than Get/Set stuff, and if the program is simple enough that you don't have to worry about you yourself forgetting things, then there will be no downside to using globals.

    For most of the simple programs I have written, I have had a module that includes several globals. Those globals will be common for all processes in the program. While I could encapsulate them in some private structure, and provide access to them through proper Get/Set functions, there is no benefit to doing so.

    If others were likely to need to maintain the code, that might not hold true, but in my case I think it is safe to say that the whole thing will be re-written in .NET before it will be maintained by a second person in VB6.

  17. #17
    PowerPoster Dave Sell's Avatar
    Join Date
    Mar 2004
    Location
    /dev/null
    Posts
    2,961
    Originally posted by szlamany

    But part of me says that a PUBLIC collection with a function or two that adds and drops entries into in - in some BASMAIN module, isn't a whole lot different than what you describe.

    Same concept - just different syntax.
    I'm more than happy to share my OO views here. You are right and you are wrong. If you look very close to the surface of the Earth it looks flat. We both know its curved. What is the difference when you are close? As you say, there isn't a whole lot of difference. I would agree. At first...

    However, when you multiply that difference by very large quantities you do not get a flat shape at all - you get a sphere, as can be easily seen from the Moon.

    My point is, good OO practices are made up of large numbers of "tiny" differences, which when your project becomes very large, will help you immensely - especially when your customer demands a fundamental change to your entire project.

    This is when you are elated you used good OO techniques all the way around. You can make bigger "changes" to more "things" with tons less effort.

    Hope my point starts sinking in... I would not ask anyone here to run out and change their old code that works. However I do ask that you bear in mind as you code new parts of projects, and especially new whole projects, that a ton of little good things add up to something great.

  18. #18
    Banned dglienna's Avatar
    Join Date
    Jun 2004
    Location
    Center of it all
    Posts
    17,901
    GLOBAL variables are good to use with OPTION EXPLICIT. If you get an error, you know that you aren't using a GLOBAL variable, and can then declare a private variable to the sub you are working in. Things like counters are PUBLIC in my program, as they always start at 1 and except for a few cases, end at the end of the loop. When I use an EXIT SUB to skip not found errors, the next sub already has the value.
    Not good in ALL circumstances of course, but not bad either, IMHO.

  19. #19

    Thread Starter
    PowerPoster Pasvorto's Avatar
    Join Date
    Oct 2002
    Location
    Minnesota, USA
    Posts
    2,951
    I went to my main module. I changed all instances of

    Global glbVariableName as ...

    to

    Public glbVariableName as ....

    Didn't notice any difference in performance. Maybe, as was stated earlier, it is just a matter of defining things in the current syntax.

    I suppose now I will have to do something about all my GOTOs.

  20. #20
    PowerPoster Dave Sell's Avatar
    Join Date
    Mar 2004
    Location
    /dev/null
    Posts
    2,961
    Originally posted by Shaggy Hiker

    If you are the only person who will ever look at your source code, you can use globals without a care in the world. After all, they will be faster in VB than Get/Set stuff, and if the program is simple enough that you don't have to worry about you yourself forgetting things, then there will be no downside to using globals.
    I respect your opinion, but I vehemently disagree. This statement is false. There are many pitfalls associated with using global variables. You have no centralized management. When does it get initialized? Who gets to do it? Who cannot? Who can reset it, and when, and under what circumstances? What about other triggers that need to be affected on mutation of those variables?

    Your statement is very misleading.

    And you MUST worry about yourself forgetting things, because 6 months down the road, when you revisit your code, you are essentially the same as a total stranger looking at someone else's code for the first time.

    However I will concede that when programs are very small none of this matters, but I am obviously not talking about toy programs.

  21. #21

    Thread Starter
    PowerPoster Pasvorto's Avatar
    Join Date
    Oct 2002
    Location
    Minnesota, USA
    Posts
    2,951
    I keep all of my global variables in one module so I can always find them quickly

  22. #22
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    35,239
    Do you also name that module with a name that will bring it to the top of an alphebetized list? I start such a module with aa just for that purpose.

  23. #23
    PowerPoster
    Join Date
    Feb 2001
    Location
    Crossroads
    Posts
    3,047
    For what its worth i dont see anything wrong with properly used global variables. You definitly have to understand Scope though.

    For example:

    This will get you into trouble easily and is BAD:
    Public i as Long 'loop variable to use in all my do/for loops

    :-)

    However if a Public declaration gets you out of passing a variable a gazillion times as an argument ... then I think it is justified.

    Just my 2 cents :-)

  24. #24

    Thread Starter
    PowerPoster Pasvorto's Avatar
    Join Date
    Oct 2002
    Location
    Minnesota, USA
    Posts
    2,951
    I have a

    Public X as integer
    Public Y as integer

    I use these for looping throughout my system..

    For X = 1 to whatever
    For Y = 3 to moreY
    Next Y
    Next X

    It hasn't caused any problems so far...

  25. #25
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    CT
    Posts
    17,882
    Since we appear to be going off topic:

    We have this as standard boilerplate for every SUB, function and event that we have. I like to have x, y, z and i, j, k looping variables and 5 strings always available.

    VB Code:
    1. Public Function FindLookup(strName As String, strData As String) As String
    2.  
    3. Dim i As Long, j As Long, k As Long, x As Long, y As Long, z As Long
    4. Dim s1 As String, s2 As String, s3 As String, s4 As String, s5 As String
    5.  
    6. Debug.Print "   FindLookup with " & strName & " and " & strData
    7. On Error GoTo Error_Handler
    8.  
    9. Begin:
    10.  
    11.     s1 = Mid$(strName, 4)
    12.  
    13.     i = 1
    14.    
    15.     Do While i <> 0
    16.         j = InStr(i + 1, strData, "=")
    17.  
    18. .
    19. .
    20. .
    21.  
    22.     Loop
    23.    
    24. Rtn_Caller:
    25.     Exit Function
    26.  
    27. Error_Handler:
    28.     Call Fatal_Error(Err.Number, Err.Source, Err.Description, "FindLookup")
    29.     Resume Rtn_Caller
    30.  
    31. End Function

  26. #26
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    35,239
    Ok, that seems reeeaally regimented to me. Do you actually have boilerplate declarations in subs and functions?

  27. #27
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    CT
    Posts
    17,882
    It's actually really a piece of cake - when you want a new SUB or FUNCTION - COPY an existing one - PASTE it in place where you want it and do a REPLACE ALL on the old function name with the new function name.

    The DEBUG.PRINT was a suggestion from a consultant 3 years ago that has made the immediate window really, really helpful.

    The standard error function is good practice.

    There are time we comment-out the DEBUG.PRINT - you don't want to see that in a MOUSE MOVE event...

  28. #28
    PowerPoster
    Join Date
    Feb 2001
    Location
    Crossroads
    Posts
    3,047
    Originally posted by Pasvorto
    I have a

    Public X as integer
    Public Y as integer

    I use these for looping throughout my system..

    For X = 1 to whatever
    For Y = 3 to moreY
    Next Y
    Next X

    It hasn't caused any problems so far...
    Sorry about hijacking the thread .. but I thought this was an improtant enough point ...

    That can very easily cause you much grief.
    Here is an example that should make you rethink your strategy:
    Run the example code and see what happens:

    VB Code:
    1. Public i As Integer
    2. Private Sub Command1_Click()
    3.     For i = 1 To 10
    4.         Call mySub
    5.         DoEvents
    6.     Next i
    7.     MsgBox "All Done"  '(but youll never get here see the msgbox!)
    8. End Sub
    9. Private Sub mySub()
    10.     For i = 1 To 5
    11.         DoEvents
    12.     Next i
    13. End Sub

  29. #29
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    35,239
    Excellent. Nasty....yet unexpected.

  30. #30
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    CT
    Posts
    17,882
    Global, public, common memory - whatever you call it - must be respected

  31. #31
    Banned dglienna's Avatar
    Join Date
    Jun 2004
    Location
    Center of it all
    Posts
    17,901
    As I stated, only occasionally to I use an EXIT SUB - to get out of a loop and the subroutine. (EXIT LOOP is different)

    I don't call subs from within loops in the first place. I would call the sub and have the loop contained from within it.

    I use loop1 and loop2 a lot.

    I don't want X and Y to get confused with mouse coordinates.

  32. #32

    Thread Starter
    PowerPoster Pasvorto's Avatar
    Join Date
    Oct 2002
    Location
    Minnesota, USA
    Posts
    2,951
    Yes, that would cause some problems. I am very cognizant of that sort of trap.

    Seems this thread has gone from
    Global vs Public
    to
    OOP/OOD
    to
    proper use (or non-use) of global varaibles at all

    Good learning experience for me.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width