diff --git a/README.adoc b/README.adoc index cb5b0333..25ee83cc 100644 --- a/README.adoc +++ b/README.adoc @@ -5790,6 +5790,39 @@ class Person end ---- +=== Avoid Dynamic Instance Variable Access [[no-dynamic-instance-variable-access]] + +Avoid `instance_variable_get` and `instance_variable_set`. +These methods bypass encapsulation and couple callers to internal implementation details. +Prefer defining explicit accessor methods instead. +Framework or library code that needs to work generically with arbitrary objects may be a justified exception. + +[source,ruby] +---- +# bad +class Person + def initialize(name) + @name = name + end +end + +person = Person.new('Alice') +person.instance_variable_get(:@name) # => 'Alice' +person.instance_variable_set(:@name, 'Bob') + +# good +class Person + attr_reader :name + + def initialize(name) + @name = name + end +end + +person = Person.new('Alice') +person.name # => 'Alice' +---- + === No Monkey Patching [[no-monkey-patching]] Do not mess around in core classes when writing libraries (do not monkey-patch them).