diff --git a/README.adoc b/README.adoc index 6a706e51..2ac10bd0 100644 --- a/README.adoc +++ b/README.adoc @@ -5742,6 +5742,54 @@ u2.send :sleep, 0 u2.__send__ ... ---- +=== Avoid Variable Reflection Methods [[avoid-variable-reflection]] + +Avoid using Ruby's variable reflection methods. They break encapsulation and make code harder to understand and maintain. + +These methods include: + +* `instance_variable_get` +* `instance_variable_set` +* `instance_variable_defined?` +* `instance_variables` +* `remove_instance_variable` +* `class_variable_get` +* `class_variable_set` +* `class_variable_defined?` +* `class_variables` +* `remove_class_variable` + +NOTE: These methods may be acceptable in framework/library code, testing utilities, serialization libraries, or debugging tools where generic object introspection is necessary. + +[source,ruby] +---- +class Person + def initialize(name) + @name = name + end +end + +person = Person.new('Alice') + +# bad - breaks encapsulation +person.instance_variable_get(:@name) +person.instance_variable_set(:@name, 'Bob') + +# good - use proper accessor methods +class Person + attr_reader :name + attr_writer :name + + def initialize(name) + @name = name + end +end + +person = Person.new('Alice') +person.name +person.name = 'Bob' +---- + == API Documentation [[api-documentation]] === YARD