Encapsulation means that the internal representation of an object is hidden from the outside. Only the object can interact with its internal data. Public methods can be created to open a defined way to access the logic inside an object.
class Document
attr_accessor :name
def initialize(name)
@name = name
end
def set_name(name)
@name = name
end
endd = Document.new('name1')
d.set_name('name1')Can easily change the value of my document name without having to know how the Document class is implemented.
From Samurails
Give an example of a poorly-encapsulated class that uses an attr_accessor. The example above is poorly encapsulated. Explain why it is a poor example of Encapsulation User should not be able to write to name directly bypassing the set_name method. Refactor the class to better use Encapsulation.
class Document
attr_reader :name
def initialize(name)
@name = name
end
def set_name(name)
@name = name
end
private
attr_writer :name
end
I don't think the class is well encapsulated in the second instance. I could still do something like this:
i.e. mess around with the Document's name from outside.
Also, you define a private
attr_writerbut never do anything with it.