PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197
Scope of Variables-VBForums
Results 1 to 21 of 21

Thread: Scope of Variables

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Nov 2018
    Posts
    157

    Scope of Variables

    I understand the different types of variable scopes (private, public, global)
    but I want to confirm there is never a conflict when having variables declared with the same name.

    For example suppose I have in a Module:
    Public myVar as Long

    Is it safe to use in one or more Private or Public Subs?
    Dim myVar as Long

    And also safe to use in one or more Private or Public Functions?
    Private Function MyFunction(myVar as Long) As Integer

    My own tests say yes, but I just want to confirm.

    Btw,
    Is there a difference between using Public and Global?
    Is there a difference between using Dim and Private?

  2. #2
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    5,627

    Re: Scope of Variables

    In all languages I've dealt with, it's the variable with the most limited scope that will take precedence. And I feel quite confident that's true in VB6.

    Edit1: But, as a practice, I try my best to not have these overlapping scoped variables.

    Edit2: Public=Global, but Public is preferred.
    Private=Dim, and I tend to use both but for different things ... old habits.
    Last edited by Elroy; May 15th, 2019 at 11:09 AM.
    Any software I post in these forums written by me is provided “AS IS” without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. Please understand that I’ve been programming since the mid-1970s and still have some of that code. My contemporary VB6 project is approaching 1,000 modules. In addition, I have a “VB6 random code folder” that is overflowing. I’ve been at this long enough to truly not know with absolute certainty from whence every single line of my code has come, with much of it coming from programmers under my employ who signed intellectual property transfers. I have not deliberately attempted to remove any licenses and/or attributions from any software. If someone finds that I have inadvertently done so, I sincerely apologize, and, upon notice and reasonable proof, will re-attach those licenses and/or attributions. To all, peace and happiness.

  3. #3
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    32,380

    Re: Scope of Variables

    Never assume it's safe... from a coding stand point, it "might be safe" ... but a conflict will likely happen... if not from the compiler, then from the organic compound involved - either yours, or someone else's, brain. So while from a programatic standpoint it might be safe to do that... from a natural, organic perspective, it won't be.


    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  4. #4

    Thread Starter
    Addicted Member
    Join Date
    Nov 2018
    Posts
    157

    Re: Scope of Variables

    I also try not to use same variable names.
    But I find that in large projects it is sometimes hard (not to have all unique names).

    You want to have a name be intuitive (for easy readability),
    but how many ways can you name say track for example, track, trk, myTrack, etc.
    when you might use it many, many times in your project.

  5. #5
    Hyperactive Member
    Join Date
    Mar 2018
    Posts
    295

    Re: Scope of Variables

    Quote Originally Posted by mms_ View Post
    but how many ways can you name say track for example, track, trk, myTrack, etc.
    your global vars should have something to indicate it is different than what you would normally type, eg "gTrack". Then it won't matter if you use trk, track, mytrack locally.

  6. #6
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    32,380

    Re: Scope of Variables

    That's because "Track" is meaningless. It has no context. What are you tracking? the number of Golf balls? The number of train tracks? Don't sacrifice clarity for brevity. VB allows you to be verbose when you need to. Don't go nuts, but don't be afraid to give your variables some context and meaning. numGolfBallsUsed has more clarity and meaning than gTrackBalls or even gTrackBallsUsed or gTrackUsed. The only time I use crap names for my variables is for temp throw away code; code that I know I'm not going to keep, or code that I know I'm going to rewrite in the next few minutes but need either try it out real quick or just get it out before I lose it in my mind (it has been known to happen).

    Track is a verb, not a noun... so I find it ambigous to use in a variable that is being used to describe a noun. Technically all variables are being used to "track" something.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  7. #7

    Thread Starter
    Addicted Member
    Join Date
    Nov 2018
    Posts
    157

    Re: Scope of Variables

    In this case track is a noun ( ie a MIDI track )

    But I hear you.



    And DllHell, I like your idea of the "g" prefix
    Last edited by mms_; May 15th, 2019 at 01:07 PM.

  8. #8
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    33,927

    Re: Scope of Variables

    Technically, track is both a verb AND a noun, as you used yourself.

    I would say that the language will behave consistently if you use two variables with the same name, but that does not mean that it is safe. If you have a global variable and a local variable with the same name, it is only "right" that the local variable be used if you want only the local variable to be used. If you forgot about the local variable and wanted to use the global, then that certainly wouldn't work, and wouldn't be considered safe. So, it is consistent behavior, you have just made it harder to work with because you will see A, and expect some form of A, but if there are two forms of A available, whether your expectations matches the behavior depends on your expectations.
    My usual boring signature: Nothing

  9. #9
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    12,894

    Re: Scope of Variables

    Quote Originally Posted by mms_ View Post
    I also try not to use same variable names.
    But I find that in large projects it is sometimes hard (not to have all unique names).

    You want to have a name be intuitive (for easy readability),
    but how many ways can you name say track for example, track, trk, myTrack, etc.
    when you might use it many, many times in your project.
    Well you really only need 3 different ways to name it.
    1: Global
    2: Module
    3: Procedure

    You may also need some variation for public and private when it applies.

    As far as I know there is no real issue with reusing a global var locally provided you declare it properly in the procedure. Failure to do so will not give you a compile error but can give you unexpected results. Other than that the main reason not to use the same names for global, module, procedure vars is to prevent confusion when reading the code.

  10. #10
    Hyperactive Member
    Join Date
    Feb 2019
    Posts
    382

    Re: Scope of Variables

    I tend to put my global variables in a UDT or Class called "cfg", so when I type "cfg.", I get intellisense, otherwise I prefix them with g_. I start with UDT, but as it gets more complex, I turn it into a class. A class could enforce data integrity between "global variables", especially arrays of UDT, for example, checking a flag or a value in a UDT to make sure that you are not reading data from a "deleted" element in an array.

  11. #11
    Hyperactive Member
    Join Date
    Mar 2018
    Posts
    295

    Re: Scope of Variables

    Quote Originally Posted by qvb6 View Post
    I tend to put my global variables in a UDT or Class called "cfg", so when I type "cfg.", I get intellisense
    we use classes since they can hold props and common functions.

    So "db.serverName" will return the server name and "db.opentable("users")" will return a recordset. Similar classes for email, file io, etc

  12. #12
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    32,380

    Re: Scope of Variables

    Quote Originally Posted by Shaggy Hiker View Post
    Technically, track is both a verb AND a noun, as you used yourself.
    That's why context is important... "track" by itself even "MyTrack" as it is held no meaning... so I had no context in what manner the OP was using it... currentMDITrack... nextMDITrack... previousMDITrack... myMDITrack... puts some context to it, makes it more meaningful. But if you're using track as your variable names, then yes, i can see how you start to get into problems with finding ways to come up with names to avoid conflicts. Which is what my point was... VB allows verbosity in names... use it. Don't sacrifice clarity for brevity.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  13. #13
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    5,627

    Re: Scope of Variables

    I'll admit that I'm not perfectly consistent. but I use CamelCase for all my variable names, always capitalizing first letter.

    And then, I preface everything with a "type":

    i = Integer or Long (sometimes l for long, but I don't like that one).
    f = Single
    d = Double
    b = Boolean
    dt = Date
    bb = Byte
    s = String
    v = Variant
    u = UDT
    o = Object

    I also sometimes use those when declaring functions, but I seem to be getting away from that, and just letting the function names stand on their own.

    And then, there's a pre-prefix if it's anything other than local to a procedure:

    m = Module level.
    g = Global (public).

    So, I'll have things like:

    dSomeVariable ... some double precision variable within a procedure.
    mvSomeVariable ... some variant declared at module level.
    gbSomeVariable ... some boolean declared with Public or Global (could be in a class).


    Now, I also name all my modules, and they have prefixes as well (but three letters):

    basSomeModule
    clsSomeModule
    frmSomeForm

    Not sure why, but I don't tend to do that for UserControls.

    When using controls on a form, I also have a three-letter convention (including my UCs, but the UCs are custom for me):

    txtSomeTextbox
    cboSomeCombo
    optSomeOptionButton
    chkSomeCheckBox
    picSomePictureBox
    lstSomeListbox
    lsvSomeListView
    treSomeTreeView
    cmdSomeButton
    etc.

    All of this helps me tremendously to stay organized. I'm sure my scheme isn't precisely like everyone esle's, but MMS, I'd strongly encourage you to adopt some scheme to use. You'll thank yourself months or years down the road.

    Also, I know there are some recommended Microsoft naming schemes. Others might provide some of those links.

    Take Care,
    Elroy
    Any software I post in these forums written by me is provided “AS IS” without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. Please understand that I’ve been programming since the mid-1970s and still have some of that code. My contemporary VB6 project is approaching 1,000 modules. In addition, I have a “VB6 random code folder” that is overflowing. I’ve been at this long enough to truly not know with absolute certainty from whence every single line of my code has come, with much of it coming from programmers under my employ who signed intellectual property transfers. I have not deliberately attempted to remove any licenses and/or attributions from any software. If someone finds that I have inadvertently done so, I sincerely apologize, and, upon notice and reasonable proof, will re-attach those licenses and/or attributions. To all, peace and happiness.

  14. #14
    Hyperactive Member
    Join Date
    Mar 2018
    Posts
    295

    Re: Scope of Variables

    There are some exhaustive style guidelines out there but I personally think they have too many restrictions and they read more like a wish list of things that could only happen in some magical code base.

    I've been tinkering with the below for many years and have tried making something that lays down some basic principals for getting things done and working well with others.
    ---

    Naming prefixes
    The type of the variable is encoded as one or more characters. The more common types are encoded as single characters while the less common types are encoded using three or four characters.

    i for integer, l for long, s for string, frm for form, etc

    Prefixes should be used as hints or guides and may not be necessary on common variables such as ID or ObjectID. For example, you do not need to write lID or lObjectID since most cases will be using the Long type. If the variable deviates from its common type (Dim ObjectID as String) consider adding an identifier to avoid confusion later (Dim sObjectID as String).

    Naming structure
    Use multiple words - but use them carefully. It can be hard to remember whether the amount due is called AmountDue or DueAmount. Start with the fundamental and generic thing and then add modifiers as necessary. An amount is a more fundamental thing (what's a "due"?), so you should choose AmountDue:

    use DateDue not DueDate
    use NameFirst not FirstName
    use StatusEnabled not EnabledStatus

    You will generally find that nouns are more generic than adjectives. Naming variables this way means that related variables tend to sort together, making cross reference listings more useful. AmountDue, AmountPastDue, AmountRefunded will be grouped together in AutoComplete to make finding things easier.

    Cradle to Grave Names
    Don't use uID, userID, usrID. Pick one name and stick with it. And stick with it everywhere you use it: source code, control names, database fields and tables, config files, registry entries, etc.

    note: this is difficult habit to learn. compare redacted to redacted. redacted is much easier to follow because of the consistent names.

    Casing
    Variables, functions, procedures, and controls use CamelCasing (capitalize the first letter in each word, no spaces between words). Constants use UPPER_CASING (capitalize all words, underscores between words):

    NavigateComplete
    SkipRecord
    MAX_RECORDS = 500
    PI = 3.14

    Procedure\Function naming
    Named according to the following conventions
    VerbNoun
    VerbNounAdjective

    Good:
    FindCustomer
    FindCustomerNext
    UpdateCustomer
    UpdateCustomerCur

    Bad:
    CustomerLookup should be LookupCustomer
    GetNextCustomer should be GetCustomerNext

    Again, naming functions this way will help group similar functions together. FindUserByName and FindUserByID will appear in the list next to each other.


    Commenting Code
    Not every line or block needs to be commented. Don’t comment obvious code that simply explains how it works. The source code and debugger will tell you how it works. The reader needs to know what you are doing or why a decision was made.

    Comments should focus on the following scenarios:
    * What you are doing
    * Where you are up to in a series of events
    * Why you have chosen a particular option
    * Any external factors that need to be known

    Consider small changes to your code to make it easier to understand. Add comments to complicated blocks to make it easier to understand what the code does. For example:

    What does this code do?:

    r = n / 2;
    while (abs(r-n/r))>t) {
    r = 0.5 * (r+(n/r));
    }
    system.out.println(r)

    A single comment can explain it:

    //square root of n with newton-raphson approx
    r = n / 2;
    while (abs(r-n/r))>t) {
    r = 0.5 * (r+(n/r));
    }
    system.out.println(r)

    Function names can also be fully descriptive:

    private double SquareRootApproximation(n) {
    ...
    ...
    }

    Note: Descriptive function names may not always be a good substitution for a proper comment. Large functions with complicated or abstracted steps may need additional comments explaining the major steps.

    Comment formatting
    Don't do this
    vb6 Code:
    1. '*********************
    2. '*  AddCustomer()    *
    3. '*                   *
    4. '*  adds a customer  *
    5. '*                   *
    6. '*********************

    It may look nice\cool (very debatable) but isn't easy to maintain


    DoEvents()
    Avoid at all costs.

    DoEvents may let events or procedures fire out of order and can lead to bugs and that are difficult to find and correct. There is almost always a better solution.

    Note: Some controls such as the webbrowser require DoEvents and you should not remove DoEvents from the code until you understand why it was added.

    Note2: by default, redacted.exe will not let you check-in code with DoEvents See redacted or redacted if you need an exception added

    GoTo
    Do not use GoTo statements unless they make the code simpler. The general consensus of opinion is that GoTo statements tend to make code difficult to follow but in some cases the exact opposite is true. If you really feel that it is necessary, go ahead and use one. Just make sure that you have thought it through and are convinced that it really is a good thing and not a hack.

    Note: GoTo statements as an integral part of error handling, so you do not have a choice

    Multiple statements per line
    Try to avoid combining multiple statements on one line. It can make it the code less legible

    MISC: IDE Fonts
    Font should accurately show the difference between letters are numbers that look similar such as upper case O and zero 0. “Consolas” is a good choice if you have clear type enabled

  15. #15
    Frenzied Member
    Join Date
    Feb 2017
    Posts
    1,727

    Re: Scope of Variables

    Quote Originally Posted by DllHell View Post
    Naming structure

    [...]

    use DateDue not DueDate
    use NameFirst not FirstName
    use StatusEnabled not EnabledStatus

    [...]

    Good:
    FindCustomer
    FindCustomerNext
    UpdateCustomer
    UpdateCustomerCur

    Bad:
    CustomerLookup should be LookupCustomer
    GetNextCustomer should be GetCustomerNext
    VB6 itself doesn't stick to this rule.

    Quote Originally Posted by DllHell View Post
    naming functions this way will help group similar functions together. FindUserByName and FindUserByID will appear in the list next to each other.
    Yes, but it is a tradeoff between that advantage and being more natural (being closer to natural language).
    FindUserByName and FindUserByID of your example are also natural.

    I tend to choose the closer to natural language option, but not always anyway (I guess more or less the same that the VB6 designers did).
    Last edited by Eduardo-; May 15th, 2019 at 06:35 PM.

  16. #16
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    5,627

    Re: Scope of Variables

    Yeah, regarding function names, rather than try to have them start with what they do, I've got module names that help with that. For instance, here are some of my module names:

    mod_Gen_Arrays
    mod_Gen_CommonDialog
    mod_Gen_Controls
    mod_Gen_FileInfo
    mod_Gen_Numbers
    mod_Gen_Registry
    etc.

    And then, when I'm naming functions, I try to come up with names that would "flow" in a sentence.

    For instance, for some of the suggested above, I might come up with:

    CustomerFound
    NextCustomer
    CustomerUpdated

    Then, when using them, I could do something like:

    If CustomerFound <> vbNullString Then ...

    And, to me, it flows like a sentence.

    But, that's just me. I'm not sure there are any hard-and-fast rules regarding function names. I'll agree that we should make them as descriptive as possible though.

    To get that "natural language" feel though, we need to develop a habit of thinking about it when we make up our function names.

    All The Best,
    Elroy
    Any software I post in these forums written by me is provided “AS IS” without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. Please understand that I’ve been programming since the mid-1970s and still have some of that code. My contemporary VB6 project is approaching 1,000 modules. In addition, I have a “VB6 random code folder” that is overflowing. I’ve been at this long enough to truly not know with absolute certainty from whence every single line of my code has come, with much of it coming from programmers under my employ who signed intellectual property transfers. I have not deliberately attempted to remove any licenses and/or attributions from any software. If someone finds that I have inadvertently done so, I sincerely apologize, and, upon notice and reasonable proof, will re-attach those licenses and/or attributions. To all, peace and happiness.

  17. #17
    Frenzied Member
    Join Date
    Feb 2017
    Posts
    1,727

    Re: Scope of Variables

    Here there is an interesting read. Some points:

    ✓ DO choose easily readable identifier names.
    For example, a property named HorizontalAlignment is more English-readable than AlignmentHorizontal.

    ✓ DO favor readability over brevity.
    The property name CanScrollHorizontally is better than ScrollableX (an obscure reference to the X-axis).

    X DO NOT use underscores, hyphens, or any other non alphanumeric characters.

    X DO NOT use Hungarian notation.

    X AVOID using identifiers that conflict with keywords of widely used programming languages.X

    DO NOT use abbreviations or contractions as part of identifier names.
    For example, use GetWindow rather than GetWin.

    X DO NOT use any acronyms that are not widely accepted, and even if they are, only when necessary.

    ✓ DO use semantically interesting names rather than language-specific keywords for type names.
    For example, GetLength is a better name than GetInt.
    Further reading: https://docs.microsoft.com/en-us/dot...ing-guidelines
    Last edited by Eduardo-; May 15th, 2019 at 10:18 PM.

  18. #18

    Thread Starter
    Addicted Member
    Join Date
    Nov 2018
    Posts
    157

    Re: Scope of Variables

    Thanks for all the advice.

    Consensus seems to be, play it safe and don't use variables of the same name.
    Other good coding practices pointed out as well.

  19. #19
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    5,627

    Re: Scope of Variables

    Quote Originally Posted by mms_ View Post
    Consensus seems to be, play it safe and don't use variables of the same name.
    Other good coding practices pointed out as well.
    For me, it's not about playing it safe. I'm completely confident about how the compiler parses out variables. For me, it's writing code that makes sense: Makes sense when I write it, makes sense to me 6 months after I write it, and makes sense to others who may read it.

    Take Care,
    Elroy
    Any software I post in these forums written by me is provided “AS IS” without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. Please understand that I’ve been programming since the mid-1970s and still have some of that code. My contemporary VB6 project is approaching 1,000 modules. In addition, I have a “VB6 random code folder” that is overflowing. I’ve been at this long enough to truly not know with absolute certainty from whence every single line of my code has come, with much of it coming from programmers under my employ who signed intellectual property transfers. I have not deliberately attempted to remove any licenses and/or attributions from any software. If someone finds that I have inadvertently done so, I sincerely apologize, and, upon notice and reasonable proof, will re-attach those licenses and/or attributions. To all, peace and happiness.

  20. #20
    Hyperactive Member
    Join Date
    Mar 2018
    Posts
    295

    Re: Scope of Variables

    Quote Originally Posted by Elroy View Post
    For me, it's writing code that makes sense: Makes sense when I write it, makes sense to me 6 months after I write it, and makes sense to others who may read it.
    well said

  21. #21
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    12,894

    Re: Scope of Variables

    Quote Originally Posted by Elroy View Post
    For me, it's not about playing it safe. I'm completely confident about how the compiler parses out variables. For me, it's writing code that makes sense: Makes sense when I write it, makes sense to me 6 months after I write it, and makes sense to others who may read it.

    Take Care,
    Elroy
    Yep, same here.

Posting Permissions

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



Featured


Click Here to Expand Forum to Full Width