Announcement

Collapse
No announcement yet.

Static variable within a method

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Static variable within a method

    I created method with a static variable in it, and then created 2 instances of the object. I noticed that the static variable is shared between the 2 instances. Is this the expected behavior? I know it can be replaced with an Instance var, but I was just curious about this.
    Scott Slater
    Summit Computer Networks, Inc.
    www.summitcn.com

  • #2
    Scott,

    That would be the expected behaviour in any OO language.

    It is generally said that static variables are variables that belong to the class. Dyamic variables belong to the instantiated object.

    Comment


    • #3
      I hope it ain't so!

      Afaik he speaks about two instances, not two references to a single instance.
      hellobasic

      Comment


      • #4
        Take a look at STATIC in the help file. No mention of Methods. Use at your own risk.
        I suppose it might be useful for something but I'm at a loss??

        James

        Comment


        • #5
          STATIC variables work as advertised and that's how they're advertised. It may be that you wanted INSTANCE instead... as you noted.

          Bob Zale
          PowerBASIC Inc.

          Comment


          • #6
            Originally posted by jcfuller View Post
            I suppose it might be useful for something but I'm at a loss??
            Code:
            CLASS MyClass
                INSTANCE internalv1     AS LONG
                INSTANCE internalv2     AS DWORD
                CLASS METHOD CREATE()
                    LOCAL TestCreations AS LONG
                    TestCreations = ME.MyCreations(0)
                    IF TestCreations = 0 THEN
                        ' specialized creation stuff
                    END IF
                    ME.MyCreations(+1)
                END METHOD
                CLASS METHOD DESTROY()
                    LOCAL TestCreations AS LONG
                    TestCreations = ME.MyCreations(-1)
                    IF TestCreations = 0 THEN
                        ' specialized destroy stuff
                    END IF
                END METHOD
                CLASS METHOD MyCreations(Bump AS LONG) AS LONG
                    STATIC CreationCount    AS LONG
                    CreationCount = CreationCount + Bump
                    METHOD = CreationCount
                END METHOD
                INTERFACE MyInterface
                    INHERIT IUNKNOWN
                    PROPERTY GET PublicCreationAccess() AS LONG
                        PROPERTY = ME.MyCreations(0)
                    END PROPERTY
                END INTERFACE
            END CLASS
            Furcadia, an interesting online MMORPG in which you can create and program your own content.

            Comment


            • #7
              Take a look at STATIC in the help file. No mention of Methods. Use at your own risk.
              I suppose it might be useful for something but I'm at a loss??
              The most common method of creating a singleton object is to use a static variable; It is one of the widest used design patterns around, and if you changed this behaviour it wouldn't work.

              Comment


              • #8
                Singleton

                Hey Trevor,

                Would you mind showing a little example of how a PB singleton would look?

                Thanks
                Start as you mean to go on.

                Comment


                • #9
                  Thanks for the answers all. I was just checking out variable "scopes" within classes by writing some experimental code. I can see the usefulness of this characteristic, but was curious if it was normal. Thanks again.
                  Scott Slater
                  Summit Computer Networks, Inc.
                  www.summitcn.com

                  Comment


                  • #10
                    Mark,

                    I'm sorry to say I do not own a copy of PB9. The version I have only allows me to use objects. I can however tell you what the pattern is because I use it all of the time in C# and VB6.

                    let me stress; this is not the only way to do it. Just the most common.

                    The object 'MySingleton' would be created as 'public non-creatable' that means you would not be able to create the object using the 'New' keyword. In VB6 that is done by setting an option in the IDE. In C# that is done by changing the default constructor to private.

                    That is important because I want total control over the creation of the object. If a programmer using my library tries to create an instance they will get a 'compile time' error. Much better than a run-time error.

                    Next I need a Factory Class that is a friend of the Singleton. It will be the responsibilty of the factory to return an instance of the Singleton. I can befriend these two classes by compiling them into the same DLL. By compiling them into the same DLL the factory will be able to create it but users of the DLL will not.

                    The factory needs a static variable that controls the creation of the object. And a method to return the object; 'GetMySingleton'
                    The choices in that method are normally;

                    1. if it already exists refuse to create a new one' throw an error or return NOTHING.
                    or
                    2. return a reference to the same object so that all instances point to the same object. This also is a method of caching the object so you need to be aware of that behaviour. (It might not be wanted).

                    In order to do option one: the static variable could be a boolean 'MySingletonCreated' then it is just

                    Code:
                    if mySingletonCreated then
                        function = NOTHING
                    else 
                        function = new MySingleton
                        mySingletonCreated = true
                    end if
                    You need to check for NOTHING on the other end of the call

                    Code:
                    obj = MyFactory.GetMySingleton()
                    if not obj is NOTHING then
                    
                    end if
                    In order to do option two: the static variable would have to be of type MySingleton 'MyCachedSingleton'; then it is just a matter of checking it in the GetMySingleton method

                    Code:
                    if MyCachedSingleton is NOTHING then
                        MyCachedSingleton = new MySingleton
                    End if
                    function = MyCachedSingleton
                    It is also important that the Factory class is a static class. That is done in C# by marking the class as static. In VB6 I set the option in the IDE to make it Global Multiuse.

                    This means that I use the class directly without creating an instance

                    So if my factory class is called MyFactory I would just use it as ClassName.FunctionName i.e MySingleton = MyFactory.GetMySingleton.

                    Some of the pattern may not be do-able in PB. I am not sure that you can create a static class for instance and use it with the class name. If this is the case you will still be able to use the pattern (modified) to create a singleton; but you will not be able to 'Enforce' a singleton. In the instances where I use singletons I need them to be enforced.
                    Last edited by Trevor Lane; 21 Feb 2009, 11:38 PM.

                    Comment


                    • #11
                      Hey Trevor,

                      Thanks for taking the time to explain that.
                      Start as you mean to go on.

                      Comment


                      • #12
                        Doesn't the concept of using a STATIC or GLOBAL variable at the "CLASS" level totally conflict with the oft-stated primary benefit of Object-Oriented-Programming that each 'instance' of an object is its own little world of code and data, and neither depends upon, cares about nor modifies data belonging to another little world?
                        Michael Mattias
                        Tal Systems (retired)
                        Port Washington WI USA
                        [email protected]
                        http://www.talsystems.com

                        Comment


                        • #13
                          Originally posted by Michael Mattias View Post
                          Doesn't the concept of using a STATIC or GLOBAL variable at the "CLASS" level totally conflict with the oft-stated primary benefit of Object-Oriented-Programming that each 'instance' of an object is its own little world of code and data, and neither depends upon, cares about nor modifies data belonging to another little world?
                          Yes in a perfect world but ....
                          Do a search on C++ Friend

                          James

                          Comment


                          • #14
                            >Do a search on C++ Friend

                            Don't think I need to go that far ......BASIC has lots of functions and features and statements which have been abused over the years... probably numerous examples right here.
                            Michael Mattias
                            Tal Systems (retired)
                            Port Washington WI USA
                            [email protected]
                            http://www.talsystems.com

                            Comment


                            • #15
                              Doesn't the concept of using a STATIC or GLOBAL variable at the "CLASS" level totally conflict with the oft-stated primary benefit of Object-Oriented-Programming that each 'instance' of an object is its own little world of code and data
                              That is a misunderstanding of the principle. Each instance of the object contains it's own methods and data. Is distinctly different to your scenario.

                              Nothing in that principle states that the object cannot also contain static data.

                              Comment


                              • #16
                                Originally posted by Trevor Lane View Post
                                That is a misunderstanding of the principle. Each instance of the object contains it's own methods and data. Is distinctly different to your scenario.
                                Nothing in that principle states that the object cannot also contain static data.
                                While that is true how do you explain the c++ Friend Function?

                                James

                                Comment


                                • #17
                                  While that is true how do you explain the c++ Friend Function?
                                  I do not understand how you think the C++ friend function contradicts the principal that each instance of a class contains its own methods and data.

                                  There is no mention in that principle about access levels or technicalities of the data and methods.

                                  Comment


                                  • #18
                                    Originally posted by Trevor Lane View Post
                                    I do not understand how you think the C++ friend function contradicts the principal that each instance of a class contains its own methods and data.

                                    There is no mention in that principle about access levels or technicalities of the data and methods.
                                    No that's not what I meant.

                                    It seems to me it violates the encapsulation concept of no access except through Class methods?

                                    James

                                    Comment


                                    • #19
                                      I was not asking about what is possible using any one of the available development products featuring support for object-oriented syntax.

                                      I was - and am -questioning the wisdom and/or consistency of an application design using data values maintained at the CLASS level rather than PROPERTIES maintained at the INSTANCE level.

                                      In for penny, in for a pound?
                                      Michael Mattias
                                      Tal Systems (retired)
                                      Port Washington WI USA
                                      [email protected]
                                      http://www.talsystems.com

                                      Comment


                                      • #20
                                        I was - and am -questioning the wisdom and/or consistency of an application design using data values maintained at the CLASS level rather than PROPERTIES maintained at the INSTANCE level.
                                        MM, You are one of the best procedural programmers I know. So perhaps you could answer the question for me. A few years ago now (I am not going to say how many) When I was learning prodedural programming I was unfortunate enough to have a lot of advice from lecturers and other more experienced programmers who told me "You should NEVER use a global variable." Of course we know now that they are just not right. There are some places where it is Best Pactice to use a global variable; and perhaps I should have been taught; "You should never use a global variable to pass values between functions." etc.

                                        It is no different in OOP. There are cases where It is best pactice to use a Class level variable.

                                        In some languages, It is almost imposible not to. That is some languages such as C# which is totally object orientated. You cannot write a line of code that is not in a class. (Not strictly true; but believe me we do not want to go into all of the nuances of C#, some people are going to shout about the ability to create a struct outside of a class but a struct in C# is just a different type of class.)
                                        As an example to get the date in PB you may use a method called DATE$. Well in C# a method cannot exist outside of a class so to get the date you use the Today method of the DateTime Class. You do not have to create an instance of this class to use the method because it is a static (Global) method. You can just use the class as is, so to get the dateyou use DateTime.Today()

                                        It is the same with all of the string functions. String is a class that contains several static methods for working with strings so you can use String.Concat(string1,string2) for instance.

                                        In a pure OOP language those static functions make perfect sense.

                                        In a procedural program it makes perfect sense for there to be functions like Date$, or LEN(somestring). But they cannot exist in pure OOP languages like C#. In fact ALL of your built in functions are just the equivalent of C# static functions in various classes.

                                        Global variables have uses and abuses in both disciplines. But you must admit that you use global methods all of the time. Unless of course you have never used any built in function. It just takes a while to see it that way.

                                        Comment

                                        Working...
                                        X