• Login
sketchucation logo sketchucation
  • Login
🤑 SketchPlus 1.3 | 44 Tools for $15 until June 20th Buy Now

Instance @variable vs class @@variable

Scheduled Pinned Locked Moved Developers' Forum
19 Posts 8 Posters 1.8k Views 8 Watching
Loading More Posts
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • N Offline
    NewOne
    last edited by 7 Oct 2009, 15:23

    I want to clear something out for me:
    When is justified using CLASS variables and when INSTANCE variables? And I don't discuss about evident situations.
    I know the difference between this two types... but in some cases it's not so evident which one is more adequate. In more cases, a instance variable, apparently will offer same results like a class variable.
    So, my question is what I should take into consideration when I decide the variable scope?
    If somebody can offer a clear answer, maybe this will be moved on a Ruby Tutorials section.

    And please don't laugh on this 😳 .
    Thanks.

    1 Reply Last reply Reply Quote 0
    • D Offline
      david.
      last edited by 7 Oct 2009, 15:40

      A very simplified, imperfect, example.

      Let's say you have 2 nice, big, powerful Ford F250 pickup trucks. One is bright red. The other is blue.

      Class var for all trucks: maxGrossWeight = 3.5 (tons)
      Instance var for truck #1: color = red
      Instance var for truck #2: color = blue

      1 Reply Last reply Reply Quote 0
      • N Offline
        NewOne
        last edited by 7 Oct 2009, 16:06

        @david. said:

        A very simplified, imperfect, example.

        Let's say you have 2 nice, big, powerful Ford F250 pickup trucks. One is bright red. The other is blue.

        Class var for all trucks: maxGrossWeight = 3.5 (tons)
        Instance var for truck #1: color = red
        Instance var for truck #2: color = blue

        Well, this is a very simplified explanation about variables, but it doesn't answer my question. For example if I want to make a webdialog interface and I include all my webdialog code inside a class.

        
        class myWebdlg
        
        def initialize
        @my_app_name = 'Test window'
        @myDlg = UI;;WebDialog.new(@my_app_name, false,"",200, 400, 600, 350, true)
        @myDlg.set_file( "Example/my_html.html" )
        end
        
        def showDialog
        @myDlg.show{}
        @myDlg.bring_to_front
        end
        
        ...#lot of code... (or cod, if it's about fishes)
        
        end #class
        
        

        In this example, it is OK to have instance variables? And if it is OK, why is? Or, if I'd better make them CLASS variables, why should I do that?

        1 Reply Last reply Reply Quote 0
        • F Offline
          fredo6
          last edited by 7 Oct 2009, 16:28

          It all depends on what you want to do.

          Just imagine for instance that you want to offer the possibility to the user to set the size of the dialog boxes. Obviously, you would need to store these 2 parameters, sx and sy, in a place which is independent from the instances of the dialog box.

          Also, let's assume you want to keep a list of the dialog boxes opened

          You would then define a function

          
          class myWebdlg
          
          #Class variables must be declared and initialized in the class
          @@xsize = 600   
          @@ysize = 350
          @@lst_dlg = []
          
          #Method to set the size(say called from a menu or another part of the application). It also works for dialog box to be created but also for dialog boxes already created and shown.
          Note that the method must be prefixed by the class name, because it is called regardless of any class instance.
          
          def myWebdlg.set_size(sx, sy)
             @@xsize = x
             @@ysize = y
             @@lst_dlg.each { |dlg| dlg.set_size @@xsize, @@ysize }
          end
          
          def initialize
             @my_app_name = 'Test window'
             @myDlg = UI;;WebDialog.new(@my_app_name, false,"",200, 400, @@xsize, @@ysize, true)
             @@lst_dlg.push @myDlg
             @myDlg.set_file( "Example/my_html.html" )
          end
          
          def showDialog
          @myDlg.show{}
          end
          
          end
          
          

          All dialog box instances would then use the same size when created or if already shown.

          That's of course a theoritical example (I am not sure you would have several dialog boxes in reality), but this gives you an idea of why you may need class variables.

          Fredo

          1 Reply Last reply Reply Quote 0
          • M Offline
            MartinRinehart
            last edited by 7 Oct 2009, 18:13

            @newone said:

            if I want to make a webdialog interface and I include all my webdialog code inside a class.

            Don't use a class just because someone once told you that "all code should be OO". This was SmallTalk/Java foolishness. Code should have classes and object instances when it really has classes and object instances.

            Ruby doesn't even put class names in a namespace, even classes in a module, so you should avoid classes unless there is some compelling reason to have them.

            Author, Edges to Rubies - The Complete SketchUp Tutorial at http://www.MartinRinehart.com/models/tutorial.

            1 Reply Last reply Reply Quote 0
            • N Offline
              NewOne
              last edited by 7 Oct 2009, 19:06

              @martinrinehart said:

              so you should avoid classes unless there is some compelling reason to have them.

              Well, Mr. Martin Rinehart... it seems that a lesson about "right way of coding" is necessary. I just don't know who will provide one. When should we use classes and when we can stick just on modules. This is what made me undertand modules: http://www.rubyfleebie.com/an-introduction-to-modules-part-1/

              1 Reply Last reply Reply Quote 0
              • F Offline
                fredo6
                last edited by 7 Oct 2009, 23:22

                @newone said:

                if I want to make a webdialog interface and I include all my webdialog code inside a class.

                That's the right way to do it in Ruby.

                @martinrinehart said:

                Don't use a class just because someone once told you that "all code should be OO". This was SmallTalk/Java foolishness. Code should have classes and object instances when it really has classes and object instances.

                Classes are simple and straightforward in Ruby, even if you plan to use only one instance. The method invokation is very natural class.method(arguments), and it allows to encapsulate variables and method names in the class namespace.

                @martinrinehart said:

                Ruby doesn't even put class names in a namespace, even classes in a module, so you should avoid classes unless there is some compelling reason to have them.

                As far as I know, classes are attached to their encapsulating module. They provide their own namespace and live in the module namespace too (just try to type Entities in the Ruby console, and then Sketchup::Entities to see the difference).

                Fredo

                1 Reply Last reply Reply Quote 0
                • Chris FullmerC Offline
                  Chris Fullmer
                  last edited by 8 Oct 2009, 00:45

                  I've got an example that helped me understand the class vs instance variable situation a little better.

                  If you have ever made a true "tool" in SketchUp, you would have made it its own class. So for example, my line tools plugin makes a line tools class. That class gets instantiated each time the user runs the plugin. I had used instance variables to remember the last line length entered by the user, so that the tool would rememeber the user's last input. But it only remembered their input while the tool weas active. Once they switched over to the select tool, and then back to my plugin, their input was lost because it was stored in an instance variable. So I switched them all to class variables. Then once they input something, that class variable would stay alive during their entire SU session.

                  Did that make sense and help at all?

                  Chris

                  Lately you've been tan, suspicious for the winter.
                  All my Plugins I've written

                  1 Reply Last reply Reply Quote 0
                  • M Offline
                    MartinRinehart
                    last edited by 8 Oct 2009, 15:46

                    @unknownuser said:

                    Classes are simple and straightforward in Ruby

                    That's certainly true, but please explain why:

                    
                    class MyUniqueName
                        # funcs and vars here
                    end
                    
                    

                    is better than:

                    
                    module MyUniqueName
                        # funcs and vars here
                    end
                    
                    

                    Author, Edges to Rubies - The Complete SketchUp Tutorial at http://www.MartinRinehart.com/models/tutorial.

                    1 Reply Last reply Reply Quote 0
                    • F Offline
                      fredo6
                      last edited by 8 Oct 2009, 16:32

                      Martin,

                      A Class allows to create instances, which are designated by variables, so very easy to manipulate.
                      It is also a good way to encapsulate an interface (what SU does with the Sketchup::Tool placeholder class)
                      Within the class statement, you can declare methods with their name, without any prefixing.

                      Personally, I always declare classes within modules. Classes is a way to manipulate objects, whereas module is a way to package the script and provide privacy via a namespace.

                      Fredo

                      1 Reply Last reply Reply Quote 0
                      • J Offline
                        Jim
                        last edited by 8 Oct 2009, 16:46

                        For a typical plugin that uses a module strictly as a namespace, an instance variable (@anytyhing) can be thought of as "global" within the module.

                        
                        module MyMod
                          @var = 1
                          def MyMod.one
                            @var # <- this is the same @var
                          end
                          def self.two
                            @var # <-- the same @var
                          end
                        end
                        
                        

                        Even if the module is split across files.

                        
                        # File1.rb
                        module MyMod
                            @var ||= 1
                            def MyMod.one
                                @var ||= 2
                                p @var
                            end
                        end
                        
                        #File2.rb
                        module MyMod
                            @var ||= 3
                            def MyMod.two
                                @var ||= 4
                                p @var
                            end
                        end
                        
                        

                        Technically, instance variables are bound to self, so you need to be able to resolve what object is self to know which instance variables are in scope.

                        I think a class variable will have the same visibility when used the same way in a module, but for a different reason.

                        Hi

                        1 Reply Last reply Reply Quote 0
                        • M Offline
                          MartinRinehart
                          last edited by 8 Oct 2009, 18:35

                          @unknownuser said:

                          Within the class statement, you can declare methods with their name, without any prefixing.

                          I find Ruby's insistence on self.xxx to define module-level functions is quite a nuisance. On the other hand, if you create a singleton instance of your class, then to manipulate anything you have to instance.xxx() whereas in the module you can call your functions without a prefix.

                          In practice, both my Rubies have used classes within modules but that's because I converted original module-less code to module-enclosed code, classes and all.

                          Author, Edges to Rubies - The Complete SketchUp Tutorial at http://www.MartinRinehart.com/models/tutorial.

                          1 Reply Last reply Reply Quote 0
                          • M Offline
                            MartinRinehart
                            last edited by 8 Oct 2009, 18:45

                            @jim said:

                            For a typical plugin that uses a module strictly as a namespace, an instance variable (@anytyhing) can be thought of as "global" within the module....

                            Even if the module is split across files.

                            Didn't know that you could have instance vars in modules, nor that you could split modules across files. Thanks.

                            Author, Edges to Rubies - The Complete SketchUp Tutorial at http://www.MartinRinehart.com/models/tutorial.

                            1 Reply Last reply Reply Quote 0
                            • J Offline
                              Jim
                              last edited by 8 Oct 2009, 18:51

                              @martinrinehart said:

                              Didn't know that you could have instance vars in modules, nor that you could split modules across files. Thanks.

                              It's one Ruby's hallmark features (for better or worser) - you can re-open a class at any time and add to it, or redefine what's there.

                              Hi

                              1 Reply Last reply Reply Quote 0
                              • N Offline
                                NewOne
                                last edited by 8 Oct 2009, 20:41

                                @jim said:

                                For a typical plugin that uses a module strictly as a namespace, an instance variable (@anytyhing) can be thought of as "global" within the module.

                                I think a class variable will have the same visibility when used the same way in a module, but for a different reason.

                                Before starting this post (and that was the reason for the post), I had some problems with instance/class variables. I noticed that instance variables act something like "globals" inside a module, but something strange happened with class variables. I could not acces class variables from outside class. I am not sure yet what was the cause...

                                1 Reply Last reply Reply Quote 0
                                • N Offline
                                  NewOne
                                  last edited by 8 Oct 2009, 21:09

                                  As I leaned since now, in ruby, variables don't store data, instead they are pointing to value. But I don't know if class variables have pointers or not? Do they are static or dynamic?

                                  1 Reply Last reply Reply Quote 0
                                  • M Offline
                                    MSP_Greg
                                    last edited by 8 Oct 2009, 21:36

                                    Boy, a lot of topics in this thread. Here's an old programmer's brief thoughts...

                                    Why use Classes - Use classes when 'things' have data/properties. I have code that exports faces from SU to a text file. One format requires all the coordinates be listed together (with an ID) in the text file. My code loops thru the faces and creates an object from each face, with layer, material, etc and coordinate info as instance variables. The loop code creates a few hashes for the coordinates; the face objects can reference that after it's created. If I didn't use classes, I'd be screwing around with crazy arrays and all sorts of stuff. Years ago, that's how one had to code, B4 OOP.

                                    Class vs Instance - Using the above example, I use class variables for switches that affect all the objects, like what data to export. Also, the coordinate hashes are class variables.

                                    All of my web dialogs are classes, not because I create a lot of them, but because the class holds data. Both data for the dialog, and data that exists after a modal dialog is closed, like the choices a user picked.

                                    Keep in mind that classes are very generic and designed so that the user can't get at the internals. That's what setters/getters are for, so the designer, if needed, can validate changes made by an object's user.

                                    HTH,

                                    Greg

                                    1 Reply Last reply Reply Quote 0
                                    • D Offline
                                      david.
                                      last edited by 9 Oct 2009, 02:47

                                      @newone said:

                                      @jim said:

                                      For a typical plugin that uses a module strictly as a namespace, an instance variable (@anytyhing) can be thought of as "global" within the module.

                                      I think a class variable will have the same visibility when used the same way in a module, but for a different reason.

                                      Before starting this post (and that was the reason for the post), I had some problems with instance/class variables. I noticed that instance variables act something like "globals" inside a module, but something strange happened with class variables. I could not acces class variables from outside class. I am not sure yet what was the cause...

                                      You shouldn't be able to access class variables outside a class (object instance) without using an accessor (a reader and/or writer). Same goes for instances variables. That's part of the reason for using classes. There really are no global variables except true global variables (eg, using '$' as the first character of the name). And, Module vars are not globally scoped, they are Module scope only.

                                      Class vars are visible (or shared) to all object instances of a class. Instance vars are visible only to a specific object instance of a class. That is why I gave the simple example using the truck above. Neither is visible outside an object instance without an accessor (using either a class method or attribute accessor).

                                      You should check out the freely available online doc... Programming Ruby for more details about classes and variables in Ruby.

                                      1 Reply Last reply Reply Quote 0
                                      • Dan RathbunD Offline
                                        Dan Rathbun
                                        last edited by 15 Jul 2010, 15:19

                                        @martinrinehart said:

                                        @unknownuser said:

                                        Within the class statement, you can declare methods with their name, without any prefixing.

                                        I find Ruby's insistence on self.xxx to define module-level functions is quite a nuisance. On the other hand, if you create a singleton instance of your class, then to manipulate anything you have to instance.xxx() whereas in the module you can call your functions without a prefix.

                                        You don't need to prefix methodnames in modules. Use a class << self block wrapper around all the methods inside the module.

                                        See my post: [info] Using Ruby Modules

                                        I'm not here much anymore.

                                        1 Reply Last reply Reply Quote 0
                                        • 1 / 1
                                        • First post
                                          Last post
                                        Buy SketchPlus
                                        Buy SUbD
                                        Buy WrapR
                                        Buy eBook
                                        Buy Modelur
                                        Buy Vertex Tools
                                        Buy SketchCuisine
                                        Buy FormFonts

                                        Advertisement