Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down