From: Florian Gilcher Date: 2009-11-29T12:05:29+09:00 Subject: Re: Class variables, instance variables, singleton; Ruby v. -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Nov 28, 2009, at 5:12 PM, Ralph Shnelvar wrote: > > So, basically, the reason that instance_variable_get is private to > Module is that one does not wish make breaking encapsulation too easy? > > I mean, it seems easy enough to break encapsulation by adding an > accessor, right? The reason that instance_variable_get exists is solely to allow dynamic lookup of instance variables to work in cases like define_method. It is not intended to be used from the outside, because it would unintentionally publish all internal state of a class. This can be easily circumvented in such a dynamic language like Ruby, but it has a big, fat warning sign attached to it. But even from the outside, it doesn't break one of the main properties of the ruby language: the uniform access principle. There is only one way to retrieve or change a value from/in an Object: by calling a method. C++ and Java have two: directly accessing a member or calling a method. In Ruby, this is especially true, because: a.foo = "bar" Is the same as sending the message :foo= to a. a.send(:foo=, "bar") where foo= is implemented as: class A def foo=(val) #internal assignment end end In every language it is easy to publish a value by adding a method. This is not "breaking encapsulation", it is intentional publishing. If you don't know what you are doing when implementing this method, no language can help you. The way Ruby handles instance variables only makes it harder to access them in ways that the class implementer intended. But even with instance_variable_get public, your only way of getting a value would still be to call that method. Which would give the class implementer the possibility to delete, change or hook that method. Regards, Florian [1]: http://en.wikipedia.org/wiki/Uniform_access_principle - -- Florian Gilcher smtp: flo@andersground.net jabber: Skade@jabber.ccc.de gpg: 533148E2 -----BEGIN PGP SIGNATURE----- Version: GnuPG/MacGPG2 v2.0.12 (Darwin) iEYEARECAAYFAksR5PMACgkQyLKU2FMxSOLjWACdH+UwQoPd9NvQdXcxygsjDVBI PLgAniLm2EMTmTnlZGne9Ep4I02D72Gb =FlTZ -----END PGP SIGNATURE-----